【问题标题】:check if a columns contains any str from list检查列是否包含列表中的任何字符串
【发布时间】:2019-05-01 23:37:47
【问题描述】:

我尝试使用 any() 来检查该列是否包含列表中的任何字符串,并使用相应的结果创建一个新列

df_data = pd.DataFrame({'A':[2,1,3], 'animals': ['cat, frog', 'kitten, fish', 'frog2, fish']})
cats = ['kitten', 'cat']
df_data['cats'] = df_data.apply(lambda row: True if any(item in cats for item in row['animals']) else False, axis = 1)

我得到了这些结果,但我不明白为什么前两行是 False :

   A       animals   cats
0  2     cat, frog  False
1  1  kitten, fish  False
2  3   frog2, fish  False

我希望只在最后一行得到 False

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    对于 pandas,你应该尽量不使用 for loop 或 apply ,我使用 DataFrame 构造函数和 isin 和 any

    df_data['cats']=pd.DataFrame(df_data.animals.str.split(', ').tolist()).isin(cats).any(1)
    df_data
       A       animals   cats
    0  2     cat, frog   True
    1  1  kitten, fish   True
    2  3   frog2, fish  False
    

    【讨论】:

      【解决方案2】:

      翻转你的迭代

      df_data['cats'] = df_data.apply(lambda row: True if any([item in row['animals'] for item in cats]) else False, axis = 1)
      
      print(df_data)
      #    A       animals   cats
      # 0  2     cat, frog   True
      # 1  1  kitten, fish   True
      # 2  3   frog2, fish  False
      

      如果你仔细观察

      item in row['animals'] for item in cats
      

      将遍历cats 并查看该项目是否在row['animals'] 中

      item in cats for item in row['animals']
      

      将遍历row['animals'] 并查看row['animals'] 的值是否在猫列表中

      【讨论】:

      • 只是好奇你是否考虑代码的速度
      • 在这种情况下,我担心向他们展示他们的代码问题。有时我试图纠正错误,有时我试图告知更好的方法。尽管当我从您的 cmets 和答案中学习新事物时,我确实很感激。此外,如果问题集足够长以使速度成为问题,我只会真正关心代码的速度。否则,可读性也不错。
      • 好吧,这很公平:-)
      猜你喜欢
      • 2012-11-15
      • 2015-03-24
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 2014-07-08
      • 2020-08-09
      相关资源
      最近更新 更多