【问题标题】:How to check if a tuple value exists in a DataFrame column如何检查 DataFrame 列中是否存在元组值
【发布时间】:2021-12-12 22:28:18
【问题描述】:

我在 DataFrame 中有一个列,其中包含字符串或字符串元组。我想检查该列中是否存在某个值元组。

s = pd.Series(['a', ('b', 'c', 'd')])

'a' in s.values

这将返回 True。然而:

('b', 'c', 'd') in s.values

返回False,带有警告:FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison

我该如何解决这个问题?

【问题讨论】:

  • 我很确定x in yfor 循环的简写。你可以做any(x==('b','c','d') for x in s)
  • 对于 numpy 不喜欢的参差不齐的嵌套序列数组似乎很奇怪。您可以改用该列表:('b', 'c', 'd') in s.tolist()
  • 使用s.tolist() 显然是最好和最简单的选择。非常感谢!

标签: python pandas dataframe tuples


【解决方案1】:

获取您的系列中对象的所有哈希值,并将其与您要查找的哈希值进行比较

【讨论】:

    【解决方案2】:

    给你:

    s = pd.Series(['a', ('b', 'c', 'd')])
    def check_tuple(x, tuple_string="('b', 'c', 'd')"):
        if str(x).find(tuple_string)>=0:
            return True
    s.apply(check_tuple)
    

    【讨论】:

      猜你喜欢
      • 2019-02-22
      • 2021-11-12
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多