您好,我正在尝试获取包含特定单词的数据框的列名,
例如: 我有一个数据框,
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
,所以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']
关于python - 如何检查数据框中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348157/