如何在 Pandas DataFrame 的 .iloc 屬性中應用切片索引器?


Pandas DataFrame 的 .iloc 是一個屬性,用於使用基於整數位置的索引值訪問 DataFrame 的元素。

屬性 .iloc 僅接受指定行和列索引位置的整數。通常,基於位置的索引值從 0 到 length-1。

超出此範圍,我們才能訪問 DataFrame 元素,否則會引發“IndexError”。但是,切片索引器不會對超出範圍的索引值引發“IndexError”,因為它允許超出範圍的索引值。

示例 1

在以下示例中,我們已將切片索引器應用於 iloc 屬性以訪問第 1 到第 3 行的值。此處,3 被排除在外。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])

print("DataFrame:")
print(df)

# Access the elements using slicing indexer
result = df.iloc[1:3]
print("Output:")
print(result)

輸出

輸出如下所示:

DataFrame:
  col1 col2
0    a   b
1    c   d
2    e   f
3    g   h

Output:
 col1 col2
1   c   d
2   e   f

iloc 屬性透過向“.iloc”屬性指定切片索引器物件,成功地從給定的 DataFrame 中訪問了 2 行元素。

示例 2

現在,讓我們將切片索引器與負邊界值一起應用於 iloc 屬性。

# importing pandas package
import pandas as pd

# create a Pandas DataFrame
df = pd.DataFrame([['a','b'],['c','d'],['e','f'],['g','h']], columns=['col1','col2'])

print("DataFrame:")
print(df)

# Apply slicing indexer with negative bound values
result = df.iloc[-4:-1]
print("Output:")
print(result)

輸出

輸出如下所示:

DataFrame:
 col1 col2
0   a   b
1   c   d
2   e   f
3   g   h

Output:
 col1 col2
0  a   b
1  c   d
2  e   f

負邊界值 [-4:-1] 被賦予 iloc 屬性。然後它返回一個包含已訪問元素的新 DataFrame。

更新於: 2022年3月8日

661 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告