首页 > 解决方案 > 如何检查列是否包含列表

问题描述

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

标签: pythonpandas

解决方案


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

推荐阅读