根据多个条件过滤数据帧索引

2023-12-03

In pandas.DataFrame.filter有没有办法使用参数“like”或“regex”,以便它们支持 OR 条件。例如:

df.filter(like='bbi', axis=1) 

将过滤列bbi以他们的名字命名,但是我如何过滤包含的列'bbi' OR 'abc' ?

一些失败的选项:

df.filter(like='bbi' or 'abc', axis=1) 

df.filter(like=('bbi' or 'abc'), axis=1) 

我会做以下事情:

Setup:

df=pd.DataFrame(np.random.randint(0,20,20).reshape(5,4),
                          columns=['abcd','bcde','efgh','bbia'])
print(df)

   abcd  bcde  efgh  bbia
0    10    17     2     7
1     7    12    18     9
2    17     7    11    17
3    14     4     2     9
4    15    10    12    11

解决方案:

Using df.filter:

df.filter(regex=r'(abc|bbi)')

   abcd  bbia
0    10     7
1     7     9
2    17    17
3    14     9
4    15    11
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据多个条件过滤数据帧索引 的相关文章

随机推荐