Python Pandas 中的 iloc 和 loc 有何不同?

让我们举个例子来理解ilocloc之间的区别。基本上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:\n", 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