Python数据格式:传递索引和i的区别

2024-10-06 12:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是示例数据:

dict_country_gdp = pd.Series([52056.01781,40258.80862,40034.85063,39578.07441],
    index = ['Luxembourg','Norway', 'Japan', 'Switzerland'])

dict_country_gdp[0]dict_country_gdp.iloc[0]之间有什么区别?你知道吗

结果是一样的,什么时候用哪个?你知道吗


Tags: 数据示例indexcountrydictseriespd区别
1条回答
网友
1楼 · 发布于 2024-10-06 12:20:32

在处理一维序列时,[]或.iloc将给出相同的结果。你知道吗

一维序列:

import pandas as pd

dict_country_gdp = pd.Series([52056.01781, 40258.80862,40034.85063,39578.07441])

dict_country_gdp

Out[]: 
0    52056.01781
1    40258.80862
2    40034.85063
3    39578.07441
dtype: float64

dict_country_gdp[0]
Out[]: 52056.017809999998

dict_country_gdp.iloc[0]
Out[]: 52056.017809999998   

多维系列:

dict_country_gdp = pd.Series([52056.01781, 40258.80862,40034.85063,39578.07441],[52056.01781, 40258.80862,40034.85063,39578.07441])

dict_country_gdp 
Out[]: 
52056.01781    52056.01781
40258.80862    40258.80862
40034.85063    40034.85063
39578.07441    39578.07441
dtype: float64

现在在这个场景中,您不能使用[]操作符访问series。你知道吗

dict_country_gdp[0]
Out[]: KeyError: 0.0

dict_country_gdp.iloc[0]
Out[]: 52056.017809999998 

iloc在访问多维序列时提供更多控制:

dict_country_gdp[0:2]
Out[]: Series([], dtype: float64)

dict_country_gdp.iloc[0:2]
Out[]: 
52056.01781    52056.01781
40258.80862    40258.80862
dtype: float64

Documentation状态:

.iloc主要基于整数位置(从轴的0到长度-1),但也可以与布尔数组一起使用。如果请求的索引器越界,iloc将引发IndexError,但允许越界索引的切片索引器除外。(这符合python/numpy切片语义)。允许的输入为:

  • 整数,例如5
  • 整数的列表或数组[4,3,0]
  • 整数为1:7的切片对象
  • 布尔数组
  • 带有一个参数的可调用函数(调用序列,数据帧 或面板),并返回用于索引的有效输出(其中 以上)

这就是为什么不能对数据帧对象使用[]运算符的原因。当涉及到数据帧和多维序列时,只能使用iloc。你知道吗

相关问题 更多 >