Python Pandas - 如何按整数位置从 DataFrame 中选择行

pythonserver side programmingprogramming更新于 2025/11/1 20:28:17

要按整数位置选择行,请使用 iloc() 函数。提及要选择的行的索引号。

创建一个 DataFrame −

dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])

使用 iloc() − 选择具有整数位置的行

dataFrame.iloc[1]

示例

以下是代码 −


import pandas as pd

# 创建 DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35]],index=['x', 'y', 'z'],columns=['a', 'b'])

# DataFrame
print"DataFrame...\n",dataFrame

# 使用 loc 选择行
print"\n通过传递标签选择行..."
print(dataFrame.loc['z'])

# 使用 iloc 选择具有整数位置的行
print"\nSelect rows by passing integer location..."
print(dataFrame.iloc[1])

输出

这将产生以下输出 −

DataFrame...
     a    b
x   10   15
y   20   25
z   30   35

通过传递标签选择行...
a   30
b   35
Name: z, dtype: int64

Select rows by passing integer location...
a   20
b   25
Name: y, dtype: int64

相关文章


有用资源