根据包含pandas中特定字符串的列名称选择列

Eri*_*c B 6 python pandas

我使用以下方法创建了一个数据框:

df = pd.DataFrame(np.random.rand(10, 3), columns=['alp1', 'alp2', 'bet1'])
Run Code Online (Sandbox Code Playgroud)

我想获得含有从每列的数据帧df具有alp在他们的名字.这只是我的问题的简单版本,所以我的真实数据框将有更多的列.

Max*_*axU 18

替代方法:

In [13]: df.loc[:, df.columns.str.startswith('alp')]
Out[13]:
       alp1      alp2
0  0.357564  0.108907
1  0.341087  0.198098
2  0.416215  0.644166
3  0.814056  0.121044
4  0.382681  0.110829
5  0.130343  0.219829
6  0.110049  0.681618
7  0.949599  0.089632
8  0.047945  0.855116
9  0.561441  0.291182

In [14]: df.loc[:, df.columns.str.contains('alp')]
Out[14]:
       alp1      alp2
0  0.357564  0.108907
1  0.341087  0.198098
2  0.416215  0.644166
3  0.814056  0.121044
4  0.382681  0.110829
5  0.130343  0.219829
6  0.110049  0.681618
7  0.949599  0.089632
8  0.047945  0.855116
9  0.561441  0.291182
Run Code Online (Sandbox Code Playgroud)


Har*_*vey 9

如果@Pedro 的回答在这里不起作用,这是为熊猫 0.25 做的官方方法

示例数据框:

>>> df = pd.DataFrame(np.array(([1, 2, 3], [4, 5, 6])),
...                   index=['mouse', 'rabbit'],
...                   columns=['one', 'two', 'three'])
Run Code Online (Sandbox Code Playgroud)
         one two three
mouse     1   2   3
rabbit    4   5   6
Run Code Online (Sandbox Code Playgroud)

按名称选择列

df.filter(items=['one', 'three'])
         one  three
mouse     1      3
rabbit    4      6
Run Code Online (Sandbox Code Playgroud)

通过正则表达式选择列

df.filter(regex='e$', axis=1) #ending with *e*, for checking containing just use it without *$* in the end
         one  three
mouse     1      3
rabbit    4      6
Run Code Online (Sandbox Code Playgroud)

选择包含 'bbi' 的行

df.filter(like='bbi', axis=0)
         one  two  three
rabbit    4    5      6
Run Code Online (Sandbox Code Playgroud)


Ped*_*ito 7

您有多种选择,这里有几个:

1 -filterlike

df.filter(like='alp')
Run Code Online (Sandbox Code Playgroud)

2 -filterregex

df.filter(regex='alp')
Run Code Online (Sandbox Code Playgroud)