[英]how to check if a value exists in a dataframe
嗨,我正在尝试获取包含特定单词的数据框的列名,
例如:我有一个数据框,
NA good employee
Not available best employer
not required well manager
not eligible super reportee
my_word=["well"]
如何检查df中是否存在“well”以及具有“well”的列名
提前致谢!
使用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
s,所以扁平化是必要的:
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']
要检查特定列,您可以简单地检查如下:
'test' in df.cloumn.values #which returns True or False
要检查完整的 df :
df.isin(["test"]).any().any() #which will return True or False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.