Windstorm1981
Windstorm1981

Reputation: 2680

Accessing Dataframe Values From Inside a Function Python Pandas

I'm having an issue accessing dataframe values from inside a function.

The beginning of my code is as follows:

def error_check(ID, error_source):

    if error_source == "A":

         marker = df1.loc[ID,'SOMETHING']

     elif error_source == "B":

         marker = df2.loc[ID,'SOMETHING']

     elif error_source == "C":

         marker = df3.loc[ID,'SOMETHING']

     else:

         pass

    ....

    return

In short, depending on the value of error_source I want to set the value of marker equal to a value found in a particular dataframe. Each dataframe has an index label equal to ID which is passed into a the function.

My question: do I have to pass each dataframe into the function by reference (and then they are treated as local objects)? or, do I need to somehow declare the dataframes globally to be accessible within the function? or 3 is there an easy way to make the dataframe accessible anywhere within my script (not just the function)?

I've seen reference to namespace but I'm not clear on its use and I've googled to find the answer to my question but haven't seen anything that really answers it.

Thanks in advance.

Upvotes: 0

Views: 588

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210872

I'd use dictionary of DFs in this case.

Demo:

dfs = {'A':df1, 'B':df2, 'C':df3}

def error_check(ID, error_source, dfs):
    if error_source in 'ABC':
        marker = dfs[error_source].loc[ID,'SOMETHING']
    else:
        pass
        ...

Upvotes: 1

Related Questions