gpt4 book ai didi

python - Pandas 列的列表理解结果为 : unhashable type: 'dict'

转载 作者:行者123 更新时间:2023-12-01 01:32:58 41 4
gpt4 key购买 nike

我下载了 Kaggle Kernel作为 Jupyter Notebook 文件,我尝试在本地系统上运行。内核在 Kaggle 上运行良好。但是,当我尝试将其作为 .ipynb 文件运行时,以下行(在单元格 4 中)抛出错误:

cols_to_drop = [col for col in train_df.columns if train_df[col].nunique(dropna=False) == 1]

返回的错误是:

TypeError: unhashable type: 'dict'

基于此堆栈溢出 question ,我明白一个字典不能用作另一个字典的键。但是,我在确定哪一段代码实际上代表字典时遇到了困难。

我已经根据此 article 中的格式尝试了代码的几个替代版本。关于列表理解。

new_list = [expression(i) for i in old_list if filter(i)]

但是,它们会产生相同的错误。

最佳答案

pd.Series.nunique在底层调用 pd.Series.unique:

def nunique(self, dropna=True):
uniqs = self.unique()
n = len(uniqs)
if dropna and isna(uniqs).any():
n -= 1
return n

pd.Series.unique使用哈希,很像 Python 的内置 set 底层:

Hash table-based unique, therefore does NOT sort.

train_df 中的一个系列中至少有一个值包含字典。字典不可散列。因此,您将看到 TypeError: unhashable type: 'dict'

要查看哪个系列包含哪些类型,您可以使用字典理解:

type_dict = {col: set(map(type, train_df[col].values)) for col in train_df}

这是一个简单的例子:

df = pd.DataFrame({'A': [1, 'a', 'b', 4, {'some_dict': 3}], 'B': list(range(5))})
type_dict = {col: set(map(type, df[col].values)) for col in df}

print(type_dict)

{'A': {dict, int, str}, 'B': {numpy.int64}}

要使用 nunique 来计算唯一项,您需要清理数据以确保您的数据框不包含不可散列的值。

关于python - Pandas 列的列表理解结果为 : unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655834/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com