根据在 pandas 中包含特定字符串的列名称选择列 [英] select columns based on columns names containing a specific string in pandas
本文介绍了根据在 pandas 中包含特定字符串的列名称选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下内容创建了一个数据框:
I created a dataframe using the following:
df = pd.DataFrame(np.random.rand(10, 3), columns=['alp1', 'alp2', 'bet1'])
我想获取一个数据框,其中包含df
中名称中具有alp
的每一列.这只是我问题的一个简单版本,因此我的实际数据框将具有更多列.
I'd like to get a dataframe containing every columns from df
that have alp
in their names. This is only a light version of my problem, so my real dataframe will have more columns.
推荐答案
替代方法:
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
这篇关于根据在 pandas 中包含特定字符串的列名称选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文