我有一个熊猫数据框,如下所示:
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的一部分。 任何帮助都将不胜感激。
提前谢谢!
我认为在pandas0.12中,你可以做如下事情:
位于pandas.DataFrame.query的文档
我认为您可能必须为此使用
lambda
函数,因为您可以测试列isin
中的值是否包含某个序列,但是pandas
似乎没有提供用于测试列中的序列是否包含某个值的函数:输出:
好吧,我已经试着找出这个问题的答案有一段时间了,但是结果是空的(基本上没有编写一个小的递归程序来扩展列表),我想这是因为,不管怎么说,乍一看,你试图做的并不是真的那么有效(Jimmy C关于列表可变的评论就在这里)而且在大熊猫身上你绝大部分时间都不会这么做。
一个更好和(我认为)更快的方法是将嵌套列表存储为列值,以便:
显然,这需要编写一个python程序,从嵌套列表中提取类别,然后将其导出到数据帧中,但是这一次命中(对于现有数据)对于使用panda分析生成的数据帧可能是值得的。
在韦斯的《数据分析的Python》一书中有一个章节叫做“计算指示器/虚拟变量”(大约330页左右),这将是一个很好的资源来进行这种操作。
抱歉,这并不能真正回答你的问题,我当然不知道它有多可行,但是,否则,你可以试试rtrwalker的解决方案,它看起来很不错,但它是开发分支,仅供参考。
相关问题 更多 >
编程相关推荐