如何获取 Pandas DataFrame 中的第 n 行?

pythonserver side programmingprogramming更新于 2025/3/13 16:44:17

要获取 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


相关文章


有用资源