pandas global data frame

22,170

Solution 1

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'.

Solution 2

By default, Python variables are not global in scope. This is by design: it would be dangerous if a function could alter variables defined outside the function. Here's a more eloquent explanation: Using global variables in a function other than the one that created them

If you want to append rows to D within your function, you could declare it as global:

global D = pd.DataFrame()

When reading a variable, Python looks in its local scope first and, if it can't find the name there, it'll start to look in the containing scopes.

Share:
22,170
Donbeo
Author by

Donbeo

Updated on December 26, 2020

Comments

  • Donbeo
    Donbeo over 3 years

    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))