1

From a menu I am calling a function that loads csv file as Pandas dataframe. I want to have the dataframe accessible and changeable from another functions. Other functions do things like, drop na etc.

How do I ensure that I am accessing and changing the dataframe in global df?

  • Place the data frame in the module top level and use inside every function/method exactly using the `global` keyword as in your question. Duplicate from https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – deponovo Sep 25 '20 at 22:17

1 Answers1

1

I don't have enough reputations to write a comment guiding you to existing solutions for your questions, so here's an answer in case you still haven't found the solution or for someone who stumbles upon this question looking for a solution.

Also, it'd be better if you provide some code, so we can see what you are trying to do with that dataframe, and understand what you mean by this part:

How do I ensure that I am accessing and changing the dataframe in global df?

You can use global or session or a function returning the dataframe or by pickling, here are few examples:

Returning df:

def get_dataFrame():
    df = pd.read_csv("some_data.csv")
    return df

Using global:

def define-df():
    global df
    df = pd.read_csv("some_data.csv") 
    return "something"   

def process-df():
    //do something with this df
    return "something"

Now you might run into error using global for a dataframe (I never get it to work), and it's not recommended to use global anyway, so you can better use session depending on your dataframe.

Using session:

def define-df():
    df = pd.read_csv("some_data.csv")
    session['DF'] = df
    return "something"

def process-df():
    df = session['DF']
    //do something with this df/session['DF']
    return "something"

Here's a que-ans which can give you a better perspective on how to use session for using variables/df across methods.

Singh
  • 504
  • 4
  • 15