在pandas中保留/切片特定列
我知道有这些选择列的方法:
df2 = df[["col1", "col2", "col3"]]
和 df2 = df.ix[:,0:2]
但我在想有没有一种方法,可以在同一次操作中从数据框的前面、中间或后面选择列,而不需要一个个列出来。
比如说,有一个数据框 df
,它的列是:col1、col2、col3、col4、col5 和 col6。
有没有办法做到像这样?
df2 = df.ix[:, [0:2, "col5"]]
我现在的情况是有几百列,常常需要根据不同的需求选择特定的列。我查过文档,但没看到类似的内容。我是不是漏掉了什么?
3 个回答
-2
我不太明白你具体在问什么。如果你想要某一列的前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
5
如果你的列名中包含可以用来筛选的信息,你可以使用 df.filter(regex='name*') 这个方法。比如,我用这个方法来筛选我有的189个数据通道,从 a1_01 到 b3_21,效果很好。
14
如果我理解正确,最简单的方法我想到的就是这样:
>>> 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]]
就可以正常工作,不过我不确定这样做是否值得。