如何按位置切割pandas DataFrame?

90
我有一个 Pandas 数据框对象,它有 1000 行和 10 列。我只想切片数据框并取前 10 行。我该怎么做?我一直在尝试使用这个:
```python df[:10] ```
我有一个有1000行和10列的Pandas数据帧对象。 我想简单地对数据帧进行切片并取前10行。如何实现?我一直在尝试使用以下代码:
```python df[:10] ```
>>> df.shape
(1000,10)
>>> my_slice = df.ix[10,:]
>>> my_slice.shape
(10,)

我的my_slice不应该是前十行吗,也就是一个10x10的数据框(data frame)吗?我怎样才能获取前十行并使my_slice成为一个10x10的数据框(Data Frame)对象呢?谢谢。

5个回答


104

您还可以方便地执行以下操作:

df[:10]


这似乎没有为我复制列名。 - Ruben

17

有多种方法可以做到这一点。以下我们将至少介绍三个选项。

为了保留原始数据框 df,我们将把切片后的数据框赋值给 df_new

最后,在时间比较部分,我们将使用一个随机数据框展示不同执行时间。


选项1

df_new = df[:10] # Option 1.1

# or

df_new = df[0:10] # Option 1.2

选项2

使用head标签

df_new = df.head(10)

对于n的负值,此函数返回除最后n行之外的所有行,相当于df[:-n][来源]

选项3

使用iloc函数

df_new = df.iloc[:10] # Option 3.1

# or

df_new = df.iloc[0:10] # Option 3.2

时间比较

对于这种特定情况,我们使用 time.perf_counter() 来测量执行时间。

       method                   time
0  Option 1.1 0.00000120000913739204
1  Option 1.2 0.00000149995321407914
2    Option 2 0.00000170001294463873
3  Option 3.1 0.00000120000913739204
4  Option 3.2 0.00000350002665072680

enter image description here

由于可能会影响执行时间的各种变量,因此这可能会根据使用的数据框架等而发生变化。


注:

  • Instead of 10 one can replace the previous operations with the number of rows one wants. For example

    df_new = df[:5]
    

    will return a dataframe with the first 5 rows.

  • There are additional ways to measure the time of execution. For additional ways, read this: How do I get time of a Python program's execution?

  • One can also adjust the previous options to a lambda function, such as the following

    df_new = df.apply(lambda x: x[:10])
    
    # or
    
    df_new = df.apply(lambda x: x.head(10))
    

    Note, however, that there are strong opinions on the usage of .apply() and, for this case, it is far from being a required method.


14

8
这已经过时了。 - Rocketq
.ix不起作用,您应该将其删除,“df[:10]”就足够了。 - Abdelsalam Hamdi

4

DataFrame[:n] 将返回前 n 行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接