python中包含字符串列表的列

2024-09-27 09:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框,如下所示:

                                          categories  review_count
0                  [Burgers, Fast Food, Restaurants]           137
1                         [Steakhouses, Restaurants]           176
2  [Food, Coffee & Tea, American (New), Restaurants]           390
...                                          ....              ...
...                                          ....              ...
...                                          ....              ...

从这个数据框中,我只想提取那些行,其中该行的“categories”列中的列表包含类别“Restaurants”。到目前为止我试过: df[[df.categories.isin('Restaurants'),review_count]]

由于数据框中还有其他列,所以我指定了要提取的这两列。但我得到了错误:

TypeError: unhashable type: 'list'

我不太明白这个错误意味着什么,因为我对熊猫很陌生。请让我知道如何实现我的目标,即仅从数据框中提取那些行,其中该行的“categories”列具有字符串“Restaurants”作为categories_list的一部分。 任何帮助都将不胜感激。

提前谢谢!


Tags: 数据dffoodcount错误reviewlistcategories
3条回答

我认为在pandas0.12中,你可以做如下事情:

df.query('"Restaurants" in categories')

位于pandas.DataFrame.query的文档

我认为您可能必须为此使用lambda函数,因为您可以测试列isin中的值是否包含某个序列,但是pandas似乎没有提供用于测试列中的序列是否包含某个值的函数:

import pandas as pd
categories = [['fast_food', 'restaurant'], ['coffee', 'cafe'], ['burger', 'restaurant']]
counts = [137, 176, 390]
df = pd.DataFrame({'categories': categories, 'review_count': counts})
# Show which rows contain 'restaurant'
df.categories.map(lambda x: 'restaurant' in x)
# Subset the dataframe using this:
df[df.categories.map(lambda x: 'restaurant' in x)]

输出:

Out[11]: 
                categories  review_count
0  [fast_food, restaurant]           137
2     [burger, restaurant]           390

好吧,我已经试着找出这个问题的答案有一段时间了,但是结果是空的(基本上没有编写一个小的递归程序来扩展列表),我想这是因为,不管怎么说,乍一看,你试图做的并不是真的那么有效(Jimmy C关于列表可变的评论就在这里)而且在大熊猫身上你绝大部分时间都不会这么做。

一个更好和(我认为)更快的方法是将嵌套列表存储为列值,以便:

df
    review_count    Burgers   Fast Food   Restaurants    Steakhouses  Food    CoffeeTea  American (New)
0            137    True      True        True           False        False   False      False
1            176    False     False       True           True         False   False      False
2            390    False     False       True           False        True    True       True   

显然,这需要编写一个python程序,从嵌套列表中提取类别,然后将其导出到数据帧中,但是这一次命中(对于现有数据)对于使用panda分析生成的数据帧可能是值得的。

在韦斯的《数据分析的Python》一书中有一个章节叫做“计算指示器/虚拟变量”(大约330页左右),这将是一个很好的资源来进行这种操作。

抱歉,这并不能真正回答你的问题,我当然不知道它有多可行,但是,否则,你可以试试rtrwalker的解决方案,它看起来很不错,但它是开发分支,仅供参考。

相关问题 更多 >

    热门问题