python - 如何检查数据框中是否存在值

标签 python pandas dataframe data-analysis

您好,我正在尝试获取包含特定单词的数据框的列名,

例如: 我有一个数据框,

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/

相关文章:

Python-子进程

python - 我的带有蒙特卡洛 dropout 的模型是否应该提供类似于确定性预测的平均预测?

python - pandas DataFrame.to_string() 从列中截断字符串

python - Pylucene 4.9.0 Ubuntu 14.04 安装 ImportError

python - Pandas DataFrame 跨行条件

python - 在 Python 中将具有不同标题的 csv 文件与 Pandas 合并

python - 仅针对有数据的时间段绘制 Pandas 日内时间序列

python - 从 Pandas 组中获取最新值(value)

python - Pandas read_excel 不读取某些 xlsx 文件,返回空数据框

python - 在构造函数中子类化 Pandas 数据框和设置字段