如何使用 .iloc 屬性訪問 pandas DataFrame 元素?


pandas.DataFrame.iloc 屬性用於使用整數位置訪問 pandas DataFrame 中的元素。它與 pandas.DataFrame 的“iat”屬性非常相似,但區別在於,“iloc”屬性可以訪問一組元素,而“iat”屬性只能訪問單個元素。

“.iloc”屬性允許使用整數、整數列表、包含整數的切片物件和布林陣列等作為輸入。

如果請求的索引超出範圍,該屬性將引發“IndexError”異常,切片索引器物件除外。

示例 1

在下面的示例中,我們使用巢狀列表和整數值建立了一個 pandas DataFrame。之後,我們使用單個整數值應用了 iloc 屬性。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))

print("DataFrame:")
print(df)

# Access the elements using iloc attribute
result = df.iloc[0]
print("Output:")
print(result)

輸出

輸出如下:

DataFrame:
    a   b   c   d
0   1   2   3   4
1  10  20  30  40
2 100 200 300 400

Output:
a    1
b    2
c    3
d    4
Name: 0, dtype: int64

iloc 屬性訪問了給定 DataFrame 中的整個第 0 行。

示例 2

讓我們透過向 iloc 屬性提供整數列表來訪問 pandas.DataFrame 中的元素。在這個示例中,我們向“iloc”屬性指定了 [0,1]。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([[1,2,3,4],[10,20,30,40],[100,200,300,400]], columns=list('abcd'))

print("DataFrame:")
print(df)

# Access the elements using a list of integers
result = df.iloc[[0,1]]
print("Output:")
print(result)

輸出

輸出如下:

DataFrame:
    a   b   c   d
0   1   2   3   4
1  10  20  30  40
2 100 200 300 400

Output:
   a  b  c  d
0  1  2  3  4
1 10 20 30 40

我們已成功使用“iloc”屬性訪問了 pandas DataFrame 中的第 0 行和第 1 行元素。結果,它返回一個新的 DataFrame 物件,如上面的輸出塊中所示。

更新於:2022年3月8日

1K+ 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.