Search code examples
pythonpandasglobal-variables

pandas global data frame


Why is this code wrong?

Isn't D a global variable?

import pandas as pd

D = pd.DataFrame()
D['z'] = [2]


def funz2(z):
    d = pd.DataFrame()
    d['z'] = z
    D = D.append(d)
    print(D)


print(funz2(4))

This is the error message

In [22]: ---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-22-68bb930462f5> in <module>()
----> 1 __pyfile = open('''/tmp/py3865JSV''');exec(compile(__pyfile.read(), '''/home/donbeo/Desktop/prova.py''', 'exec'));__pyfile.close()

/home/donbeo/Desktop/prova.py in <module>()
     14 
     15 
---> 16 print(funz2(4))

/home/donbeo/Desktop/prova.py in funz2(z)
     10     d = pd.DataFrame()
     11     d['z'] = z
---> 12     D = D.append(d)
     13     print(D)
     14 

UnboundLocalError: local variable 'D' referenced before assignment

EDIT: If variables are not automatically global. Why does it work?

x = 3 

def funz(z):
    return z * x

print(funz(4))

Solution

  • Your funz2 can certainly access the D variable that you declared outside of it.

    The problem you see is because you have declared another D variable local to the funz function with the line that starts with D=. This local one takes precedence over the other globalish one and thus you get the exception.

    What you can do is as Alex Woolford suggests and declare the D in the funz function as global using the global statement in effect saying 'see that D there, I don't wanna declare no local D var there I want it to reference that other global one'.