pandas 获取数据帧的前几行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33424098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:07:16  来源:igfitidea点击:

Obtaining the first few rows of a dataframe

pythonpandas

提问by Jojo

Is there a way to get the first n rows of a dataframe without using the indices. For example, I know if I have a dataframe called dfI could get the first 5 rows via df.ix[5:]. But, what if my indices are not ordered and I dont want to order them? This does not seem to work. Hence, I was wondering if there is another way to select the first couple of rows. I apologize if there is already an answer to this. I wasnt able to find one.

有没有办法在不使用索引的情况下获取数据帧的前 n 行。例如,我知道如果我有一个名为的数据框,df我可以通过df.ix[5:]. 但是,如果我的索引没有被订购并且我不想订购它们怎么办?这似乎不起作用。因此,我想知道是否有另一种方法来选择前几行。如果已经有答案,我深表歉意。我没能找到一个。

回答by EdChum

Use head(5)or iloc[:5]

使用head(5)iloc[:5]

In [7]:
df = pd.DataFrame(np.random.randn(10,3))
df

Out[7]:
          0         1         2
0 -1.230919  1.482451  0.221723
1 -0.302693 -1.650244  0.957594
2 -0.656565  0.548343  1.383227
3  0.348090 -0.721904 -1.396192
4  0.849480 -0.431355  0.501644
5  0.030110  0.951908 -0.788161
6  2.104805 -0.302218 -0.660225
7 -0.657953  0.423303  1.408165
8 -1.940009  0.476254 -0.014590
9 -0.753064 -1.083119 -0.901708

In [8]:
df.head(5)

Out[8]:
          0         1         2
0 -1.230919  1.482451  0.221723
1 -0.302693 -1.650244  0.957594
2 -0.656565  0.548343  1.383227
3  0.348090 -0.721904 -1.396192
4  0.849480 -0.431355  0.501644

In [11]:
df.iloc[:5]

Out[11]:
          0         1         2
0 -1.230919  1.482451  0.221723
1 -0.302693 -1.650244  0.957594
2 -0.656565  0.548343  1.383227
3  0.348090 -0.721904 -1.396192
4  0.849480 -0.431355  0.501644