【问题标题】:pandas function return multiple values error - TypeError: unhashable type: 'list'pandas 函数返回多个值错误 - TypeError: unhashable type: 'list'
【发布时间】:2018-10-05 07:32:21
【问题描述】:

我编写了一个 pandas 函数,它运行良好(我的代码的倒数第二行)。当我尝试将函数的输出分配给数据框中的列时,出现错误TypeError: unhashable type: 'list'

我发布了 similar 的内容,我正在使用以下函数中该问题的答案中显示的方法。但它仍然失败:(

import pandas as pd
import numpy as np

def benford_function(value):
    if value == '':
        return []

    if ("." in value):
         before_decimal=value.split(".")[0]
         if len(before_decimal)==0:
             bd_first="0"
             bd_second="0"

         if len(before_decimal)>1:
             before_decimal=before_decimal[:2]
             bd_first=before_decimal[0]
             bd_second=before_decimal[1]
         elif len(before_decimal)==1:
             bd_first="0"
             bd_second=before_decimal[0]

         after_decimal=value.split(".")[1]
         if len(after_decimal)>1:
             ad_first=after_decimal[0]
             ad_second=after_decimal[1]
         elif len(after_decimal)==1:
             ad_first=after_decimal[0]
             ad_second="0"
         else:
             ad_first="0"
             ad_second="0"



    else:
        ad_first="0"
        ad_second="0"
        if len(value)>1:
             bd_first=value[0]
             bd_second=value[1]
        else:
            bd_first="0"
            bd_second=value[0]
    return pd.Series([bd_first,bd_second,ad_first,ad_second])



df = pd.DataFrame(data = {'a': ["123"]})


df.apply(lambda row: benford_function(row['a']), axis=1)

df[['bd_first'],['bd_second'],['ad_first'],['ad_second']]= df.apply(lambda row: benford_function(row['a']), axis=1)

【问题讨论】:

    标签: python pandas function return


    【解决方案1】:

    变化:

    df[['bd_first'],['bd_second'],['ad_first'],['ad_second']] = ...
    

    df[['bd_first', 'bd_second', 'ad_first', 'ad_second']] = ...
    

    这将修复您的类型错误,因为索引元素必须是可散列的。您尝试通过传递单元素列表元组来索引 Dataframe 的方式会将这些单元素列表中的每一个解释为索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-11
      • 2018-06-04
      • 1970-01-01
      • 2015-02-11
      • 2015-03-16
      • 2017-04-25
      • 2019-10-11
      • 2020-03-27
      相关资源
      最近更新 更多