import pandas as pd
df = pd.DataFrame({"col1": ["a", "b", "c", ["a", "b"]]})
Run Code Online (Sandbox Code Playgroud)
我有一个这样的数据框,我想在该列中找到包含列表的行。我尝试了 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
Run Code Online (Sandbox Code Playgroud)
对于更大的数据帧,这需要永远。
以下是所需输出的样子:
col1
c 1
b 1
[a,b] 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
列表是可变的,它们无法比较,因此您既不能对值进行计数,也不能将它们设置为索引。你需要转换为tuple 或者(感谢@CameronRiddell)能够计算:set
df['col1'].apply(lambda x: tuple(x) if isinstance(x, list) else x).value_counts()
Run Code Online (Sandbox Code Playgroud)
输出:
c 1
b 1
a 1
(a, b) 1
Name: col1, dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
166 次 |
| 最近记录: |