【问题标题】:Python dictionary.get TypeError: unhashable type: 'Series'Python dictionary.get TypeError: unhashable type: \'Series\'
【发布时间】:2022-08-11 06:54:43
【问题描述】:

我正在尝试解决这个问题,但我在这里遇到错误并且不知道如何正确修复它。 我的字典如下所示。

dict_wu = {\'1004\': \'UG\', \'1028\': \'MG\', \'1043\': \'MG\', \'2801\': \'UG\', \'2802\': \'UG\', \'2803\': \'MG\'}

我的数据框如下:

    AC      Units
2   1002    UG
3   1004    MG
6   1004    UG
7   1005    UG
..   ..     ..
91  1028    MG
92  1028    UG
93  1028    UG

我试图通过s = dict_wu.get(df[\'AC\'].astype(str))制作一个系列

回溯(最近一次通话最后): 文件 \"f:...\\pull_differences.py\",第 35 行,在 s= dict_wu.get(df[\'AC\'].astype(str)) TypeError:不可散列的类型:\'Series\'

我该如何解决?我将如何测试两列的条件以创建如下所示的新列?

df[\'test\'] = np.where(dict_wu.get(df[\'AC\'].astype(str)) == df[\'Units\'] ,True ,False)

    标签: python pandas dictionary


    【解决方案1】:

    pd.Series.map 非常适合这个。

    df['AC'].astype(str).map(dict_wu)
    

    结合您的其他代码:

    df['test'] = np.where(df['AC'].astype(str).map(dict_wu) == df['Units'], True, False)
    

    输出:

    >>> df
          AC Units   test
    2   1002    UG  False
    3   1004    MG  False
    6   1004    UG   True
    7   1005    UG  False
    91  1028    MG   True
    92  1028    UG  False
    93  1028    UG  False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 2020-05-11
      • 2018-08-12
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多