您好我正在尝试获取包含特定字词的数据框的列名
例如: 我有一个数据框,
NA good employee
Not available best employer
not required well manager
not eligible super reportee
my_word=["well"]
如何检查df中是否存在“well”以及具有“well”
的列名称提前致谢!
答案 0 :(得分:5)
使用DataFrame.isin
检查所有列,DataFrame.any
检查每行至少一个True
:
m = df.isin(my_word).any()
print (m)
0 False
1 True
2 False
dtype: bool
然后通过过滤获取列名称:
cols = m.index[m].tolist()
print(cols)
[1]
数据:
print (df)
0 1 2
0 NaN good employee
1 Not available best employer
2 not required well manager
3 not eligible super reportee
详情:
print (df.isin(my_word))
0 1 2
0 False False False
1 False False False
2 False True False
3 False False False
print (df.isin(my_word).any())
0 False
1 True
2 False
dtype: bool
编辑转换嵌套list
后,必须flattening:
my_word=["well","manager"]
m = df.isin(my_word).any()
print (m)
0 False
1 True
2 True
dtype: bool
nested = df.loc[:,m].values.tolist()
flat_list = [item for sublist in nested for item in sublist]
print (flat_list)
['good', 'employee', 'best', 'employer', 'well', 'manager', 'super', 'reportee']
答案 1 :(得分:3)
要检查特定列,您只需进行以下检查:
'test' in df.cloumn.values #which returns True or False
用于检查完整的df:
df.isin(["test"]).any().any() #which will return True or False