【问题标题】:how to check if a value exists in a dataframe如何检查数据框中是否存在值
【发布时间】:2018-05-01 02:00:09
【问题描述】:

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

例如: 我有一个数据框,

NA              good    employee
Not available   best    employer
not required    well    manager
not eligible    super   reportee

my_word=["well"]

如何检查df中是否存在“well”以及具有“well”的列名

提前致谢!

【问题讨论】:

  • 只有一个字?
  • 不,有时不止一个
  • 而且应该是子串?
  • 是的,字符串列表

标签: python pandas dataframe data-analysis


【解决方案1】:

使用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

编辑转换后得到嵌套lists,所以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']

【讨论】:

  • 好的,如何将这些列值添加到my_word,我们需要一个一个追加还是任何pandas方式添加
  • 如果两者都是列表,只需使用+,如my_word += colsmy_word = my_word + cols
  • 不,不只是列名,我想在cols中添加所有数据列的值
  • 不,它适用于 df 中的所有数据。
  • 不幸的是,它不是数字。否则我会使用 numpy
【解决方案2】:

对于特定列的检查,您可以简单地检查如下:

'test' in df.cloumn.values #which returns True or False

用于签入完整的 df :

df.isin(["test"]).any().any() #which will return True or False

【讨论】:

    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2014-06-26
    • 2020-12-31
    • 2022-06-13
    • 2016-09-21
    • 2020-12-16
    相关资源
    最近更新 更多