3
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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
RDS
  • 53
  • 4

1 Answers1

2

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74