Predictive Hacks

How to use global variables inside a function

global variables

We are sure that at some point in your programming life you have received an error like UnboundLocalError: local variable ‘x’ referenced before assignment. In this post, we will show you how you can skip this error easily along with a useful hack for Pandas DataFrames.

Let’s say that we have a function that when it takes as input a negative number it returns 0. We want to apply it in a data frame but somehow we want to count how many times the function returned 0. Having said that we need a variable, let’s call it “counter”. To use this variable inside our function without any errors, we need to add this line of code: global counter (the name of the variable).

#this is out fucntion

counter=0
def test(x):
    #at this point we are calling the global variable counter
    global counter
    if x<0:
        x=0
        counter = counter+1
        return(x)
    else:
        return(x)

Let’s apply this function to the following DataFrame

data=pd.DataFrame({"A":[-1,1,-2,3,12,-6,2,45,12]})
print(data)
    A
0  -1
1   1
2  -2
3   3
4  12
5  -6
6   2
7  45
8  12
data['A'].apply(test)
0     0
1     1
2     0
3     3
4    12
5     0
6     2
7    45
8    12

Now that the function is applied to our data frame, If we call the variable “counter” it holds how many times the function took as input a negative number.

print(counter)
3

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

fuzzy matching
Python

Fuzzy Joins Tutorial

We have provided examples of how you can apply fuzzy joins in R and we assume that you are familiar

data science journey
Miscellaneous

My Journey as a Data Science Blogger

Μy Background My Studies Back in 2001, I entered university to study Statistics. During my first year, I ran my