George Liu George Liu - 20 days ago 9
Python Question

How to convert df name strings back to df's?

I have several dataframes, such as df1, df2 etc. then i made a list of the names of these df's like

lst = ['df1', 'df2']


Now, I want to use these df's in a function "my_func()"

my_func(dataframe=df1)

my_func(dataframe=df2)


...

How can i express the list of dataframes in a loop, so that i can call different df's in my_func? (the way below does't work, since I'm calling strings instead of df's...)

for i in lst:
my_func(dataframe=i)


Thanks!

Answer

I would argue that storing the name of your data-sets as strings, and then try to pass the string as a argument is counter productive.

Instead, what I would do is create a dictionary with all your data-sets as values to string keys, and pass the dictionary objects into your function.

my_frames = {'df1' : [1,2,3], 'df2' : [4,5,6]}

def my_func(dataframe):
    ... do work on dataframe ...

for df_name, df_obj in my_frames.items():
    print('Doing work on:', df_name)
    my_func(df_obj)

Another nifty thing with dictionaries and functions is that you can expand the dictionary as named parameters right off the bat.

my_frames = {'temperature' : 25.5, 'wind' : 4.6}

def weather(temperature=None, wind=None):
    print('The temp is:', temperature, 'and the wind speed is:', wind)

weather(**my_frames)

But that's just a little side note.

Comments