0

I am creating multiple dataframes with a function I have written and I want to be able to assign the name of the dataframe as an argument in the function.

def execute_query(query, df):
    conn.cursor().execute(query)
    df = pd.read_sql(query, conn)

    return df

q1 = """
select foo
from bar
"""

execute_query(q1, 'market_share_df') 

I have written the function above and when I call it, it returns a dataframe with the proper data. However, it doesn't seem like the variable name as been assigned "market_share_df". Unsure of how to do this, any ideas are welcome. Thanks

1 Answer 1

1

In your function, the variable df is just being re-assigned to be the value of the pandas function, so the name is lost.

Why don't you just make a list of data frames and append the list with the new data frame and then access them by index?

Or, make a dictionary of data frames with the key values as the names you want, and then add the new frames to the dictionary as key-value pairs? then you could get the data frame by name from the dictionary...

To do this, just pass in the dictionary as a parameter of your function.

Sign up to request clarification or add additional context in comments.

1 Comment

@Mitchell.Laferla comment back if you are stuck... Don't want to prevent any learning here! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.