如何在 Pandas DataFrame 中获取第 n 行?
要获取PandasDataFrame中的第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