在pandas中保留/切片特定列

2024-04-23 13:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这些列切片方法:

df2 = df[["col1", "col2", "col3"]]df2 = df.ix[:,0:2]

但是,我想知道是否有一种方法可以在同一个切片中从数据帧的前/中/尾对列进行切片,而不必具体列出每个列。

例如,具有列:col1、col2、col3、col4、col5和col6的数据帧df

有办法这样做吗?

df2 = df.ix[:, [0:2, "col5"]]

在这种情况下,我有成百上千的列,并且经常需要为不同的请求分割特定的列。我已经检查过文档,还没有看到类似的东西。我忽略了什么吗?


Tags: 数据方法文档df情况切片col2col3
3条回答

如果列名包含可以筛选的信息,则可以使用df.filter(regex='name*')。 我用这个在我的189个数据通道从a1u01到b3u21之间进行过滤,它工作得很好。

不知道你到底在问什么。如果您想要特定列的前5行和后5行,可以执行以下操作

df = pd.DataFrame({'col1': np.random.randint(0,3,1000),
               'col2': np.random.rand(1000),
               'col5': np.random.rand(1000)}) 
In [36]: df['col5']
Out[36]: 
0     0.566218
1     0.305987
2     0.852257
3     0.932764
4     0.185677
...
996    0.268700
997    0.036250
998    0.470009
999    0.361089
Name: col5, Length: 1000 
In [38]: df['col5'][(df.index < 5) | (df.index > (len(df) - 5))]
Out[38]: 
0      0.566218
1      0.305987
2      0.852257
3      0.932764
4      0.185677
996    0.268700
997    0.036250
998    0.470009
999    0.361089
Name: col5

或者,更一般地说,您可以编写一个函数

In [41]: def head_and_tail(df, n=5):
    ...:     return df[(df.index < n) | (df.index > (len(df) - n))] 
In [44]: head_and_tail(df, 7)
Out[44]: 
     col1      col2      col5
0       0  0.489944  0.566218
1       1  0.639213  0.305987
2       1  0.000690  0.852257
3       2  0.620568  0.932764
4       0  0.310816  0.185677
5       0  0.930496  0.678504
6       2  0.165250  0.440811
994     2  0.842181  0.636472
995     0  0.899453  0.830839
996     0  0.418264  0.268700
997     0  0.228304  0.036250
998     2  0.031277  0.470009
999     1  0.542502  0.361089 

IIUC,我能想到的最简单的方法是这样的:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame(np.random.randn(5, 10))
>>> df[list(df.columns[:2]) + [7]]
          0         1         7
0  0.210139  0.533249  1.780426
1  0.382136  0.083999 -0.392809
2 -0.237868  0.493646 -1.208330
3  1.242077 -0.781558  2.369851
4  1.910740 -0.643370  0.982876

其中,list调用不是可选的,因为否则,Index对象将尝试将自身向量添加到7。

可能会出现类似于numpy的r_这样的特殊情况

df[col_[:2, "col5", 3:6]]

会有用的,尽管我不知道这是否值得。

相关问题 更多 >