【问题标题】:How to filter a DataFrame column of lists for those that contain a certain item如何过滤包含特定项目的列表的 DataFrame 列
【发布时间】:2015-11-23 16:14:03
【问题描述】:

如果我想为包含特定术语的字符串过滤一列字符串,我可以这样做:

df = pd.DataFrame({'col':['ab','ac','abc']})
df[df['col'].str.contains('b')]

返回:

   col
0   ab
2  abc

如何过滤包含特定项目的列表列?例如,来自

df = pd.DataFrame({'col':[['a','b'],['a','c'],['a','b','c']]})

如何获取所有包含“b”的列表?

         col
0     [a, b]
2  [a, b, c]

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    你可以像这样使用apply。

    In [13]: df[df['col'].apply(lambda x: 'b' in x)]
    Out[13]: 
             col
    0     [a, b]
    2  [a, b, c]
    

    虽然一般来说,将列表存储在 DataFrame 中有点尴尬 - 您可能会发现一些更易于使用的不同表示(列表中每个元素的列、MultiIndex 等)。

    【讨论】:

    • @chrisb 如果您有一个很大的DataFrame 并且您不知道条目的数量(或者想要避免非常多的列),您将如何处理?
    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2020-09-22
    • 1970-01-01
    • 2023-03-29
    • 2021-01-14
    相关资源
    最近更新 更多