【问题标题】:TypeError while mapping DataFrame Columns using Python dict使用 Python dict 映射 DataFrame 列时出现 TypeError
【发布时间】:2018-12-13 03:58:33
【问题描述】:

我尝试使用这样的映射将 Pandas 数据框的列转换为 int 值(假设给定的数据框:my_dataframe 和列:target_column):

targets = my_dataframe[target_column].unique()
map_to_int = {name: n  for n, name in enumerate(targets)}

在 Pandas 中使用 Python 3.6 我想知道为什么

一)

my_dataframe['Integer-Column'] = map_to_int[my_dataframe[target_column]]

导致

TypeError: 'Series' 对象是可变的,因此它们不能被散列

同时

B)

my_dataframe['Integer-Column'] = my_dataframe[target_column].replace(map_to_int)

工作正常。

我想了解为什么会发生这种情况。是否有任何魔法可以替代没有抛出 TypeError 或者我错过了其他东西?我已经知道,dict-keys 是不允许改变的。但我仍然很难真正理解这一点,因为:

    words = my_dataframe[target_column].unique()
    # words = ['car' 'bike' 'plain']

    foo = 'car'
    map_to_int[foo] = 0
    foo = 'bike'
    map_to_int["bike"] = 1

任何帮助我理解为什么 B) 工作而没有 A) 麻烦的尝试将不胜感激。

【问题讨论】:

  • 我在这里找到了一些关于字符串令人困惑的部分的解释:stackoverflow.com/questions/9097994/… foo 的示例映射显然有效,因为标签 foo 后面的字符串 'car' 或相应的 'bike' 是不可变的。即使标签 foo 可以指向各种“不可变目标”。

标签: python pandas dictionary dataframe typeerror


【解决方案1】:

您的解决方案不起作用,因为您尝试使用 map_to_int[my_dataframe[target_column]]pd.Series 对象用作字典键。

此外,我建议您仅在特定情况下使用replace;对于字典映射,您通常应该使用pd.Series.map,即my_dataframe[target_column].map(map_to_int)。详情请见Replace values in a pandas series via dictionary efficiently

但是这个功能已经在 Pandas 中实现为Categorical Data。我建议您使用分类数据作为将系列中的项目映射到整数的有效且语法简洁的方式。

这是一个例子:

df = pd.DataFrame({'col1': ['a', 'b', 'c', 'a', 'b', 'a', 'd']})

df['col1'] = df['col1'].astype('category').cat.codes

print(df)

   col1
0     0
1     1
2     2
3     0
4     1
5     0
6     3

【讨论】:

    【解决方案2】:

    显然my_dataframe[target_column] 是python(3.6) 认为可变的东西。在 dict 中使用可变的东西作为键会抛出提到的 TypeError 。 因此,用它调用像 map_to_int 这样的字典会引发错误。

    在版本 B) 中仍使用字典 map_to_int,但未明确提及字典中的键。此外,它们是targets 中所包含的任何内容的不可变表示。因此,当替换函数 (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) 使用字典时,它会使用那些不可变的键。因此,没有理由抛出 TypeError,也就是观察到了什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      相关资源
      最近更新 更多