如何在 Pandas DataFrame 中獲取第 n 行?


要獲取 Pandas DataFrame 中的第 n 行,我們可以使用 iloc() 方法。例如,df.iloc[4] 將返回第 5 行,因為行號從 0 開始。

步驟

  • 製作二維、可變尺寸、可能異構的表格資料df
  • 列印輸入 DataFrame,即df
  • 初始化變數nth_row
  • 使用iloc()方法獲取第 n 行。
  • 列印返回的 DataFrame。

示例

import pandas as pd

df = pd.DataFrame(
   dict(
      name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
      marks=[89, 23, 100, 56, 90],
      subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
   )
)

print "Input DataFrame is:\n", df
nth_row = 3
df = df.iloc[nth_row]
print "Row ", nth_row, "of the DataFrame is: \n", df

輸出

Input DataFrame is:
    name   marks   subjects
0   John    89         Math
1  Jacob    23      Physics
2    Tom   100    Chemistry
3    Tim    56      Biology
4   Ally    90      English

Row 3 of the DataFrame is:
name            Tim
marks            56
subjects    Biology
Name: 3, dtype: object

更新於:2023-09-06

4.1 萬+ 次觀看

開啟你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.