python - 如何检查列是否包含列表
问题描述
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
解决方案
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
推荐阅读
- java - 404 错误 - 在 Google 云平台 vm 中运行已部署的 Java 时
- neo4j - 如果存在或不存在,列表中的 neo4j 匹配
- python - 通过 HTTPS 使用代理的 Python 请求因代理错误而失败
- flutter - Dart:不覆盖泛型方法具有类似于返回类型的泛型参数类型
- r - ggplot2。如何使 geom_bar 堆积图 y 范围 0-100%?
- html - 如何使用带有上下文的 Material UI 的 Input API 的错误道具和 css
- asp.net-core - 在本地从 Mac 连接到 Windows 以获取 Asp.net 核心 API
- android - com.google.gson.ExclusionStrategy 类型定义了多次
- html - 为什么我的标题不能正确显示我的 GraphQL 提供的共享图像缩略图?
- java - 春季启动异步