Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to panda concatenate on list with string dataframe names?

This may sound silly but I have list containing dataframe names and I am trying to concatenate those dataframes based on for loop or list comprehension or just pd.concat() them.

Code sample:

import pandas as pd

df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})


print(df1)
print(df2)

This concatenation works, that I understand

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# ideally this is what I should have as list
users_list = [df1,df2]


print(users_list)

# this works that I know
print(pd.concat(users_list,ignore_index = True))

Below is my situation and this is not working. So how can I handle this ?

# but this is what I have
users_list2 = ['df1','df2']

print(users_list2)


# but this is what I am trying to achieve as I have list of dataframe names due to some processing
print(pd.concat(users_list2,ignore_index = True))

So I am basically facing error due to users_list2 containing names/string dataframes and not the dataframes.

Appreciate any help here.

>Solution :

The problem is that you have two strings in users_list2. If you want to concatenate the dataframes based on that list, first you must evaluate the strings to variables.

You can use the following code:

import pandas as pd

df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})

users_list2 = ['df1','df2']

dataframes = pd.concat([eval(df_name) for df_name in users_list2])

I hope this helps.
Best regards

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading