Skip to main content
 首页 » 编程设计

python之Pandas :TypeError:无法散列的类型: 'list'

2025年01月19日10虾米姐

我有以下 df:

df = pd.DataFrame( 
    [ 
        [["John Muller"], "person", [8866155845]], 
        [["Innovation Division"], "company", np.nan], 
        [["Carol Sway"], "person", [8866155845]], 
    ], 
    columns=["name", "kind", "phone"], 
) 
 
# Out: 
#                     name     kind         phone 
# 0          [John Muller]   person  [8866155845] 
# 1  [Innovation Division]  company           NaN 
# 2           [Carol Sway]   person  [8866155845] 

我想查找电话号码的重复项。但是 df 中的对象是列表,所以使用:

df.duplicated('phone')  

将产生错误:

TypeError: unhashable type: 'list' 

请您参考如下方法:

您还可以使用 applymap解决这个问题非常方便的函数:

# get duplicated row 
df2 = df[df.applymap(lambda x: x[0] if isinstance(x, list) else x).duplicated('phone')] 
 
print(df2) 
 
           name    kind         phone 
2  [Carol Sway]  person  [8866155845]