python - 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'): 错误的跟踪
解决方案
您可能有一列内容是列表。
由于 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
推荐阅读
- azure - 是否可以(通过不同的支持)将 Azure 驱动器附加到 Azure 应用服务实例?
- c++ - 这两个条件有何不同?
- javascript - Javascript:如何将“选定”分配给“选项”元素
- javascript - javascript错误说array.some不是一个函数
- c++ - 如何在两个整数之间找到斐波那契数?
- python - 为什么选择列的“重命名”不能与 lambda 函数一起使用?
- pandas - 索引 csv 文件时 for 循环如何工作?
- swift - iOS 相机 CPU 使用率
- c# - 我正在尝试在 y 轴上设置我的精灵位置,但由于某种原因它保留了 0 位置
- ruby-on-rails - 使用 RVM 安装 Ruby 时如何修复错误?