Python Pandas——如何從 DataFrame 中選擇多行


若要從 DataFrame 中選擇多行,請使用 : 運算子設定範圍。首先,使用別名匯入所需的 pandas 庫 −

import pandas as pd

現在,建立一個新的 Pandas DataFrame −

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

使用 : 運算子選擇多行 −

dataFrame[0:2]

示例

以下是程式碼 −

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', '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])

# selecting multiple rows
print"\nSelect multiple rows..."
print(dataFrame[0:2])

輸出

這將產生以下輸出 −

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

Select rows by passing label...
a   40
b   45
Name: z, dtype: int64

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

Select multiple rows...
     a    b
w   10   15
x   20   25

更新於: 2021 年 9 月 14 日

3K+ 瀏覽次數

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告