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

connect with sql
R

How to Connect R with SQL

Need to Connect R with SQL It is common for Data Analysts/Scientists to connect R with SQL. For that reason,

[the_ad_group id="232"]
[the_ad id="2133"]