Python Pandas 中的 iloc 和 loc 有何不同?
pandasserver side programmingprogramming更新于 2025/4/17 0:22:17
我们举个例子来了解 iloc 和 loc 之间的区别。基本上,loc[0] 返回 0 索引处的值,而 iloc[0] 返回系列中第一个位置处的值。
步骤
创建一个带有轴标签(包括时间序列)的一维 ndarray。
打印输入系列。
使用 loc[0] 打印第 0 个索引处的值。
使用 iloc[0] 打印系列表第一个位置处的值。
示例
import pandas as pd s = pd.Series(list("AEIOU"), index=[2, 1, 0, 5, 8]) print "Input series is:
", s print "Value at index=0:", s.loc[0] print "Value at the 1st location of the series:", s.iloc[0]
输出
Input series is: 2 A 1 E 0 I 5 O 8 U dtype: object Value at index=0: I Value at the 1st location of the series: A