如何将切片索引器应用于 pandas DataFrame.iloc 属性?

pandasserver side programmingprogramming更新于 2025/5/20 9:07:17

pandas DataFrame.iloc 是一个属性,用于使用基于整数位置的索引值访问 DataFrame 的元素。

属性 .iloc 仅采用指定行和列索引位置的整数值。通常,基于位置的索引值从 0 到长度 1 表示。

只有超出此范围,我们才能访问 DataFrame 元素,否则会引发"IndexError"。但切片索引器不会引发"IndexError"对于越界索引值,因为它允许越界索引值。

示例 1

在下面的示例中,我们将切片索引器应用于 iloc 属性,以访问第 1 至第 3 行的值。这里排除了 3。

# 导入 pandas 包
import pandas as pd

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

print("DataFrame:")
print(df)

# 使用切片索引器访问元素
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 属性。

# 导入 pandas 包
import pandas as pd

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

print("DataFrame:")

print(df)

# 应用具有负边界值的切片索引器
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


相关文章