Skip to main content
 首页 » 编程设计

Python Pandas 数据格式化 : Difference in passing index and iloc

2025年04月02日9zengkefu

这是示例数据:

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] 有什么区别?

虽然结果相同,但什么时候使用哪个?

请您参考如下方法:

当您使用一维序列时,[] 或 .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 

现在在这种情况下,您无法使用 [] 运算符访问系列。

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),但也可以与 bool 数组一起使用。如果请求的索引器越界,.iloc 将引发 IndexError,但允许越界索引的切片索引器除外。 (这符合 python/numpy 切片语义)。允许的输入是:

  • 一个整数,例如5
  • 整数列表或数组 [4, 3, 0]
  • 具有整数 1:7 的切片对象
  • bool 数组
  • 一个带有一个参数的可调用函数(调用 Series、DataFrame 或 Panel) 并返回用于索引的有效输出(其中之一 以上)

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