返回值包含字符串 pandas 的所有列 [英] return all columns with values that contain string pandas
本文介绍了返回值包含字符串 pandas 的所有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框.我想在数据框中查找包含字符串abc"的所有列,并返回这些字段的列表,如下例所示.如果我正在寻找行,我会使用 isin,但我不确定如何获取列.非常感谢任何提示.
I have a dataframe like the one below. I would like to find all columns in the dataframe that contain a string ‘abc’ and return a list of those fields like the example below. If I was looking for the rows I would use isin, but I'm not sure how to get the columns. Any tips are greatly appreciated.
示例:
Print df
Field1 Field2 Field3
f_abc 23 dog
Df3 bb ju
Return
Field1
推荐答案
您可以通过 df.columns
上的列表理解来完成此操作.
You can accomplish this with list comprehension on df.columns
.
首先让我们创建一个示例数据框:
First let's create an example dataframe:
df = pd.DataFrame(columns=["A", "B", "C"], data=[['abc']*3]*3)
df['D'] = 'ab'
结果:
A B C D
0 abc abc abc ab
1 abc abc abc ab
2 abc abc abc ab
现在让我们只打印包含abc"的列:
Now let's print only the columns that contain 'abc':
print([col for col in df.columns if df[col].str.contains("abc").any()])
['A', 'B', 'C']
['A', 'B', 'C']
这篇关于返回值包含字符串 pandas 的所有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文