Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting UnboundLocalError in data exploration coding [duplicate]

Tags:

python

pandas

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

df['gender'].apply(amount_total)

Error:

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
like image 683
RDS Avatar asked Jun 17 '26 13:06

RDS


1 Answers

mt and ft are global variables, maybe you need to state that:

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)

However, you should do this instead of apply:

mt, ft = df['gender'].value_counts() * amount
like image 167
Quang Hoang Avatar answered Jun 19 '26 03:06

Quang Hoang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!