首页 > 解决方案 > Pandas dataFrame.nunique() : ("unhashable type : 'list'", 'occured at index columns')

问题描述

我想将 .nunique() 函数应用于完整的数据帧。

在下面的屏幕截图中,我们可以看到它包含 130 个特征。数据框的形状和列的屏幕截图。 目标是获得每个特征的不同值的数量。我使用以下代码(适用于另一个数据帧)。

def nbDifferentValues(data):
    total = data.nunique()
    total = total.sort_values(ascending=False)
    percent = (total/data.shape[0]*100)
    return pd.concat([total, percent], axis=1, keys=['Total','Pourcentage'])

diffValues = nbDifferentValues(dataFrame)

并且代码在第一行失败,我收到以下错误,我不知道如何解决(“unhashable type : 'list'”,'occured at index columns')错误的跟踪

标签: pythonpandas

解决方案


您可能有一列内容是列表。

由于 Python 中的列表是可变的,因此它们是不可散列的。

import pandas as pd

df = pd.DataFrame([
    (0, [1,2]),
    (1, [2,3])    
])

#  raises "unhashable type : 'list'" error
df.nunique()

解决方案:不要在数据框中使用可变结构(如列表)

df = pd.DataFrame([
    (0, (1,2)),
    (1, (2,3))    
])

df.nunique()

#  0    2
#  1    2
#  dtype: int64

推荐阅读