BirdBud
BirdBud

Reputation: 193

How to use a for loop to create multiple dataframes with different names

for key in CatDict:
    CatName = CatDict[key]['name']
    print('This is the ' + CatName + 'info')
    **Problem Area (CatName + 'DF')** = CalcDF[CalcDF.Cat == CatDict[key]['number']]

Basically what I am trying to do is create a new dataframe that is named by concatenating 'CatName' with the string 'DF' for every iteration of this loop.

I have been having a lot of trouble with that and I am not sure if what I am trying to do is feasible.

The dataframes are already formed outside the for loop I am just doing this to assign them the data that I want

Thank you

Upvotes: 0

Views: 580

Answers (2)

RJ Adriaansen
RJ Adriaansen

Reputation: 9619

You are trying to create variable variable names. This is not recommended. Rather you could create a dictionary of dataframes with their variable names as keys:

dataframes = {key[‘name’] + 'DF': CalcDF[CalcDF.Cat == CatDict[key]['number']] for key in CatDict}

Upvotes: 1

You may utilize the built-in function exec as:

for key in CatDict:
CatName = CatDict[key]['name']
print('This is the ' + CatName + 'info')
exec('{}DF = CalcDF[CalcDF.Cat == CatDict[key]['number']]'.format(CatName)) 

Upvotes: 0

Related Questions