Concatenate multiple existing dataframes using names of dataframes included in a list


actually I am economist and not a programmer, I hope there is a good Samaritan who can help me out.

I have a list called iShares:

iShares = ['IE0005042456', 'IE00B1FZS574', 'IE00B0M62Q58', 'IE00BF4RFH31', 'IE0031442068', 'IE00BGL86Z12', 'IE00BD45KH83']

Also I have a list of dataframes with identical structure:


I would like to concatenate these dataframes to only one data frame with the name Lookup_Sector. This is possible by hardcoding the names:

Lookup_Sector = pd.concat([Lookup_Sector_IE0005042456, Lookup_Sector_IE00B1FZS574, Lookup_Sector_IE00B0M62Q58, Lookup_Sector_IE00BF4RFH31, Lookup_Sector_IE0031442068, Lookup_Sector_IE00BGL86Z12, Lookup_Sector_IE00BD45KH83])

But what I rather would like to is not to hardcode and instead be more flexible and use the list iShares by first creating another list with the names of the dataframes, called Lookup_Sector_list:

Lookup_Sector_list = ['Lookup_Sector_' + i for i in iShares]

Then in the next step I would love to concetenate by using a for loop:

for i in Lookup_Sector_list:
    Sector = pd.concat([Lookup_Sector_list[i]]) 

If I do so I get an error:

TypeError: list indices must be integers or slices, not str

How can I concatenate the dataframes without hardcoding the names and instead using the list iShares?

TY so much in advance.


Since all your dataframes are in the global environment, You can select them using globals()[dat] and then concatenate them:

pd.concat([globals()['Lookup_Sector_' + i ]for i in iShares])

Answered By – onyambu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published