我在python pandas中有一个数据帧。数据帧的结构如下:
a b c d1 d2 d3
10 14 12 44 45 78
我想选择以d开头的列。在python中有没有简单的方法来实现这一点。
发布于 2015-06-13 01:04:16
您可以这样使用DataFrame.filter
:
import pandas as pd
df = pd.DataFrame(np.array([[2,4,4],[4,3,3],[5,9,1]]),columns=['d','t','didi'])
>>
d t didi
0 2 4 4
1 4 3 3
2 5 9 1
df.filter(regex=("d.*"))
>>
d didi
0 2 4
1 4 3
2 5 1
其思想是按regex
选择列
发布于 2015-06-13 01:12:38
使用select
import pandas as pd
df = pd.DataFrame([[10, 14, 12, 44, 45, 78]], columns=['a', 'b', 'c', 'd1', 'd2', 'd3'])
df.select(lambda col: col.startswith('d'), axis=1)
结果:
d1 d2 d3
0 44 45 78
如果您不习惯使用正则表达式,这是一个很好的解决方案。
发布于 2021-06-23 00:57:29
您可以对索引(本例中为列)使用startswith
方法:
df.loc[:, df.columns.str.startswith('d')]
或使用正则表达式的match
:
df.loc[:, df.columns.str.match('^d')]
https://stackoverflow.com/questions/30808430
复制相似问题