[英]pandas function return multiple values error - TypeError: unhashable type: 'list'
我已經編寫了一個pandas函數,它運行正常(代碼的第二行)。 當我嘗試將函數的輸出分配給數據幀中的列時,出現錯誤TypeError: unhashable type: 'list'
我發布了類似的內容,並且正在使用以下功能中該問題的答案中所示的方法。 但是仍然失敗了:(
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)
更改:
df[['bd_first'],['bd_second'],['ad_first'],['ad_second']] = ...
至
df[['bd_first', 'bd_second', 'ad_first', 'ad_second']] = ...
這將解決您的類型錯誤,因為索引元素必須是可哈希的。 您嘗試通過傳遞單元素列表的元組索引到Dataframe中的方式會將這些單個元素列表中的每一個解釋為索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.