如何检查数据框中是否存在值
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
for check all columns and 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
EDIT 转换后得到嵌套 list
s,所以 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']
对于特定列的检查,您可以简单地检查如下:
'test' in df.cloumn.values #which returns True or False
用于检查完整的 df :
df.isin(["test"]).any().any() #which will return True or False
嗨,我正在尝试获取包含特定单词的数据框的列名,
例如: 我有一个数据框,
NA good employee
Not available best employer
not required well manager
not eligible super reportee
my_word=["well"]
如何检查 df 中是否存在 "well" 以及具有 "well"
的列名提前致谢!
使用 DataFrame.isin
for check all columns and 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
EDIT 转换后得到嵌套 list
s,所以 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']
对于特定列的检查,您可以简单地检查如下:
'test' in df.cloumn.values #which returns True or False
用于检查完整的 df :
df.isin(["test"]).any().any() #which will return True or False