[英]How to check if a column contains list
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
列表是可變的,它們無法進行比較,因此您既不能計算值也不能將它們設置為索引。 您需要轉換為tuple
或 (感謝@CameronRiddell)能夠數數:set
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.