如何检查一个列是否包含列表

6
import pandas as pd

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

我有一个像这样的数据框,我想找到包含该列中列表的行。我尝试使用value_counts()函数,但它花费了很长时间,最后还报错了。以下是错误信息:
TypeError                                 Traceback (most recent call last)
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.map_locations()

TypeError: unhashable type: 'list'
Exception ignored in: 'pandas._libs.index.IndexEngine._call_map_locations'
Traceback (most recent call last):
  File "pandas/_libs/hashtable_class_helper.pxi", line 1709, in pandas._libs.hashtable.PyObjectHashTable.map_locations
TypeError: unhashable type: 'list'
c         1
a         1
[a, b]    1
b         1
Name: col1, dtype: int64

对于更大的数据框,这将需要很长时间。

以下是期望的输出结果:

col1
c       1
b       1
[a,b]   1
dtype: int64
2个回答

3

迭代行,并按以下条件检查列中obj的类型:type(obj) == list

import pandas as pd

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

for ind in df.index:
   print (type(df['col1'][ind]) == list)

以下是结果:

False
False
False
True

2

列表是可变的,它们不能进行比较,因此您既不能计算值也不能将它们设置为索引。您需要转换为元组(感谢@CameronRiddell)才能进行计数:

df['col1'].apply(lambda x: tuple(x) if isinstance(x, list) else x).value_counts()

输出:

c         1
b         1
a         1
(a, b)    1
Name: col1, dtype: int64

2
一个 set 也是可变的,如果他们想要类似于 set 的东西,那么它不是必须是 frozenset 吗? - Cameron Riddell
@CameronRiddell 那真是我犯傻了。谢谢你指出来。回答已更新。 - Quang Hoang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接