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:
", 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

更新於: 2021 年 8 月 30 日

265 次瀏覽

開始你的職業

完成本課程以獲得認證

開始
廣告
© . All rights reserved.