Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中搜索dataframe的所有列中的字符串_Python_Pandas_Dataframe - Fatal编程技术网

在Python中搜索dataframe的所有列中的字符串

在Python中搜索dataframe的所有列中的字符串,python,pandas,dataframe,Python,Pandas,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 Tru

我试图在数据帧的所有列中查找字符串

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
但是,上面的代码只返回布尔值,而不是我想要的格式(以表格形式显示行和列),这可以在特定列中搜索时实现:

df[df.A == 'a']

   A  B
0  a  b

有人能帮忙吗?

创建布尔
数据框
,并按以下方式检查每行至少一个
True

详细信息

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

如果要检查
子字符串
s,请使用
布尔数据帧

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)]
或通过中的
进行元素检查:

df = df[df.applymap(lambda x: 'a' in x).any(axis=1)]

print (df)
    A    B
0  ad    b
2   e  asw

这是一种使用恰当命名的
np.logical\u或
的方法

import pandas as pd, numpy as np

df = pd.DataFrame([['a', 'b'], ['c', 'd'], ['e', 'a']], columns=["A", "B"])

mask = np.logical_or.reduce([df[col] == 'a' for col in df])

df[mask]

#    A  B
# 0  a  b
# 2  e  a
此方法也适用于
str.contains
。例如:

mask = np.logical_or.reduce([df[col].str.contains('a', na=False) for col in df])

搜索多个字符串怎么样?@JunchenLiu-然后使用
df=df[df.apply(lambda x:x.str.contains('a | b | c')).any(axis=1)]
mask = np.logical_or.reduce([df[col].str.contains('a', na=False) for col in df])