Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to iterate over dataframes while using their name as a string?

Tags:

python

pandas

I have three different Pandas dataframes

df_1
df_2
df_3

I would like to loop over the dataframes, do some computations, and store the output using the name of the dataframe. In other words, something like this

for my_df in [df_1, df_2, df_3]:
  my_df.reset_index(inplace=True)
  my_df.to_csv('mypath/' + my_df +'.csv')

Output files expected:

'mypath/df_1.csv', 'mypath/df_2.csv' and 'mypath/df_3.csv'

I am struggling doing so because df_1 is an object, and not a string. Any ideas how to do that?

Thanks!

like image 708
ℕʘʘḆḽḘ Avatar asked Apr 17 '26 04:04

ℕʘʘḆḽḘ


1 Answers

Another more general solution is create dict with column names and then loop by items():

d = {'df_1':df_1,'df_2':df_3, 'df_3':df_3}
for k, my_df in d.items():
    my_df.reset_index(inplace=True)
    my_df.to_csv('mypath/' + k +'.csv')

Another possible solution is use another list with dataframes names, then enumerate and get value of name by position:

names = ['a','b','c']
print ({names[i]: df for i, df in enumerate([df_1, df_2, df_3])})
like image 117
jezrael Avatar answered Apr 18 '26 16:04

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!