在Python中的数据框所有列中搜索字符串 [英] Searching for string in all columns of dataframe in Python
问题描述
我正在尝试在数据框的所有列中找到一个字符串.
I am trying to find a string in all columns of a dataframe.
import pandas as pd
df = pd.DataFrame([['a', 'b'], ['c', 'd'], ['e', 'a']], columns=["A", "B"])
for col in df:
df[col].str.contains('a')
0 True
1 False
2 False
Name: A, dtype: bool
0 False
1 False
2 True
Name: B, dtype: bool
但是,上面的代码仅返回布尔值,而不返回我想要的格式(以表格形式显示行和列),这可以在特定列中搜索时实现:
However, the code above returns only the booleans and not the format that I want (displays the rows and columns in table form), which can be achieved when searching in a specific column:
df[df.A == 'a']
A B
0 a b
任何人都可以帮忙吗?
推荐答案
创建布尔值DataFrame
,并通过DataFrame.any
并按
Create boolean DataFrame
and check at least one True
per row by DataFrame.any
and filter by boolean indexing
:
df = df[df.eq('a').any(axis=1)]
print (df)
A B
0 a b
2 e a
详细信息:
print (df.eq('a'))
A B
0 True False
1 False False
2 False True
print(df.eq('a').any(axis=1))
0 True
1 False
2 True
dtype: bool
如果要检查substring
,请使用 str.contains
表示boolean DataFrame
:
If want check substring
s use str.contains
for boolean DataFrame
:
df = pd.DataFrame([['ad', 'b'], ['c', 'd'], ['e', 'asw']], columns=["A", "B"])
print (df)
A B
0 ad b
1 c d
2 e asw
df = df[df.apply(lambda x: x.str.contains('a')).any(axis=1)]
或 applymap
in
进行明智的检查:
df = df[df.applymap(lambda x: 'a' in x).any(axis=1)]
print (df)
A B
0 ad b
2 e asw
这篇关于在Python中的数据框所有列中搜索字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!