如何在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP