Python Pandas - 如何透過整數位置從 DataFrame 中選擇行


要按整數位置選擇行,請使用 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

# 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

更新時間:2021 年 9 月 16 日

774 次觀看

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.