【问题标题】:Using a list as a value in a pandas dataframe使用列表作为熊猫数据框中的值
【发布时间】:2017-11-20 16:40:08
【问题描述】:

我有一些数据要插入到数据框中。数据为columns= ['Title', 'Category']。对于每个标题,我都有一个或多个类别,我决定将类别作为列表插入。所以我的 df 看起来像这样:

In [39]: title_cat_df
Out[39]: 
    Title      Category
0  Title1  [Cat1, Cat2]
1  Title3        [Cat5]
2  Title2  [Cat3, Cat4]
...
...
...

但是我不知道这是否是 pythonic/pandaionic(?!) 方法,因为我偶然发现了一些问题,例如使用 isin 查找特定类别:

In [41]: test_df['Category'].isin(cat_list)
Out[41]: TypeError: unhashable type: 'list'

在这种情况下,表示类别的更好方法是什么,并希望能够在特定类别中查找标题?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    将列转换为sets 并使用& 与转换为set 的列表的交集:

    cat_list = ['Cat1','Cat2', 'Cat4']
    print (test_df['Category'].apply(set) & set(cat_list))
    0     True
    1    False
    2     True
    Name: Category, dtype: bool
    

    boolean indexing的最后过滤器:

    test_df = test_df[test_df['Category'].apply(set) & set(cat_list)]
    print (test_df)
        Title      Category
    0  Title1  [Cat1, Cat2]
    2  Title2  [Cat3, Cat4]
    

    【讨论】:

    • 这很适合我目前的方法。我还用 500 万行的主要数据框对其进行了测试。它确实冻结了我的笔记本电脑几分钟,但最终还是通过了,所以谢谢。但是,根据我在数据框中使用列表收集的内容并不是很惯用,但是当每个条目没有特定数量的类别时,还能做什么?
    • 是的,我同意,如果使用 listssets 它不是 pandas 的原生格式。唯一的解决方案应该是从列表中创建标量,但缺点是更大的 DataFrame,例如从 3 行的样本中得到 5 :(
    猜你喜欢
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 2023-03-14
    • 2019-10-12
    • 2019-05-07
    • 1970-01-01
    相关资源
    最近更新 更多