gpt4 book ai didi

python - 在数据探索编码中获取 UnboundLocalError

转载 作者:行者123 更新时间:2023-12-04 15:26:52 24 4
gpt4 key购买 nike

mt=0
ft=0
def amount_total(g):
if g=="male":
mt=mt+amount
else:
ft=ft+amount

df['gender'].apply(amount_total)

错误:

UnboundLocalError                         Traceback (most recent call last)
<ipython-input-19-5a85616e6d1c> in <module>
7 ft=ft+amount
8
----> 9 df['gender'].apply(amount_total)

~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4040 else:
4041 values = self.astype(object).values
-> 4042 mapped = lib.map_infer(values, f, convert=convert_dtype)
4043
4044 if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()

<ipython-input-19-5a85616e6d1c> in amount_total(g)
3 def amount_total(g):
4 if g=="male":
----> 5 mt=mt+amount
6 else:
7 ft=ft+amount

UnboundLocalError: local variable 'mt' referenced before assignment

最佳答案

mtft 是全局变量,也许你需要说明:

mt=0
ft=0
def amount_total(g):
global mt
global ft
if g=="male":
mt=mt+amount // what's amount anyway?
else:
ft=ft+amount

df['gender'].apply(amount_total)

但是,您应该这样做而不是apply:

mt, ft = df['gender'].value_counts() * amount

关于python - 在数据探索编码中获取 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62087971/

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