【问题标题】:Pandas dataframe select rows where a list-column contains a specific set of elementsPandas 数据框选择列表列包含特定元素集的行
【发布时间】:2020-11-15 12:36:27
【问题描述】:

这是以下帖子的后续内容:Pandas dataframe select rows where a list-column contains any of a list of strings

我希望能够从选择列表中选择包含确切字符串对的行(其中 selection= ['cat', 'dog'])。

开始 df:

  molecule            species
0        a              [dog]
1        b       [horse, pig]
2        c         [cat, dog]
3        d  [cat, horse, pig]
4        e     [chicken, pig]

我想要的df:

  molecule            species
2        c         [cat, dog]

我尝试了以下方法,它只返回了列标签。

df[pd.DataFrame(df.species.tolist()).isin(selection).all(1)]

【问题讨论】:

    标签: pandas string list


    【解决方案1】:

    一种方法:

    df['joined'] = df.species.str.join(sep=',')
    selection = ['cat,dog']
    filtered = df.loc[df.joined.isin(selection)]
    

    这不会找到具有不同排序的案例(即'dog,cat''horse,cat,pig'),但如果这不是问题,那么它可以正常工作。

    【讨论】:

      【解决方案2】:

      这会找到任何东西。

      import pandas as pd
      selection = ['cat', 'dog']
      mols = pd.DataFrame({'molecule':['a','b','c','d','e'],'species':[['dog'],['horse','pig'],['cat','dog'],['cat','horse','pig'],['chicken','pig']]})
      mols.loc[np.where(pd.Series([all(w in selection for w in mols.species.values[k]) for k in mols.index]).map({True:1,False:0}) == 1)[0]]
      

      如果您想查找至少包含列表中元素的任何行(并且可能还有其他元素),请使用:

      mols.loc[np.where(pd.Series([all(w in mols.species.values[k] for w in selection) for k in mols.index]).map({True:1,False:0}) == 1)[0]]
      

      这是一个有趣的矩阵作为选择器的应用。使用转置后的 mols 将 0 向量和指向 mols 中哪些行符合您的标准的向量相乘:

      mols.to_numpy().T.dot(pd.Series([all(w in mols.species.values[k] for w in selection) for k in mols.index]).map({True:1,False:0}))
      

      另一个(更具可读性)的解决方案是为 mols 分配条件为 True 的列,将其映射到 0 和 1 并查询该列等于 1 的 mols。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-10
        • 2020-05-28
        • 2019-07-12
        • 2020-04-08
        • 2020-01-10
        • 1970-01-01
        • 2016-05-28
        • 2021-12-20
        相关资源
        最近更新 更多