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

阅读 1202 收藏 0 点赞 0 评论 0

要获取 Pandas DataFrame 中的第 n 行,我们可以使用该iloc()方法。例如,df.iloc[4]将返回第 5 行,因为行号从 0 开始。

步骤

  • 制作二维、大小可变、潜在异构的表格数据,df。

  • 打印输入数据帧,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

评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号