0

Is it possible to update the value of a global python variable from within a pandas lambda function?

I'm trying to

  1. use the value of this global variable in my lambda function
  2. change its value within the lambda function
  3. use the updated value in lambda function that's called on the subsequent rows

I've tried to declare the value of my global variable outside of the lambda function, but it's not accessible from within the lambda function itself. I also tried to pass it using

def do_something(x, global_var):
   print(global_var)

   if global_var > 0:
      global_var = -1
      return x/2
   elif global_var <= 0:
      global_var = 1
      return 2*x


global_var = 5
df.apply(lambda x, global_var = global_var: do_something(x, global_var)

but updating global_variable from within the function doesn't update it globally. How, then, can I update the value of this variable from inside the lambda function?

13
  • 3
    Does this answer your question? Python Global Variable not updating Commented Oct 22, 2021 at 21:36
  • Hi, can you update your code to an MWE so we can play around with it? Commented Oct 22, 2021 at 21:37
  • 1
    It's been my experience that when you start asking if you can do these sorts of things with a lambda, it's better to just use a function. Commented Oct 22, 2021 at 21:37
  • @Woodford this is perfect, I hadn't realized how to refer to global variables from within the lambda function. Thank you! Commented Oct 22, 2021 at 21:39
  • 1
    @mapf the comment by Woodford seems to have led me to the right place, I'll update the question to reflect this. Thank you for the looking into this! Commented Oct 22, 2021 at 21:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.