在Pandas DataFrame中使用比较列表的问题 [英] Issues using compare lists in pandas DataFrame
本文介绍了在Pandas DataFrame中使用比较列表的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在pandas中有一个DataFrame,其中一种列类型是int上的列表,像这样:
I have a DataFrame in pandas with one of the column types being a list on int, like so:
df = pandas.DataFrame([[1,2,3,[4,5]],[6,7,8,[9,10]]], columns=['a','b','c','d'])
>>> df
a b c d
0 1 2 3 [4, 5]
1 6 7 8 [9, 10]
我想使用d建立一个过滤器,但是正常的比较操作似乎不起作用:
I'd like to build a filter using d, but the normal comparison operations don't seem to work:
>>> df['d'] == [4,5]
0 False
1 False
Name: d, dtype: bool
但是当我逐行检查时,我得到了期望的结果
However when I inspect row by row, I get what I would expect
>>> df.loc[0,'d'] == [4,5]
True
这是怎么回事?如何进行列表比较?
What's going on here? How can I do list comparisons?
推荐答案
这是一个奇怪的问题,它可能与列表不可散列有关 我会申请:
It is a curious issue, it probably has to do with the fact that list are not hashable I would go for apply:
df['d'].apply(lambda x: x == [4,5])
当然,如DSM所建议的,以下工作可以实现:
Of course as suggested by DSM, the following works:
df = pd.DataFrame([[1,2,3,(4,5)],[6,7,8,(9,10)]], columns=['a','b','c','d'])
df['d'] == (4,5)
另一种解决方案是使用list comprehension
:
Another solution is use list comprehension
:
df[[x == [4, 5] for v in df['col2']]]
这篇关于在Pandas DataFrame中使用比较列表的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文