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

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

创建一个数据帧 -

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

使用整数位置选择行iloc()-

dataFrame.iloc[1]

示例

以下是代码 -

import pandas as pd

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

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

# select rows with loc
print"\nSelect rows by passing label..."
print(dataFrame.loc['z'])

# select rows with integer location using iloc
print"\nSelect rows by passing integer location..."
print(dataFrame.iloc[1])
输出结果

这将产生以下输出 -

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

Select rows by passing label...
a   30
b   35
Name: z, dtype: int64

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