How to name dataframes in a for-loop?

Viewed 623

I am attempting to name multiple dataframes using a variable in a for loop. Here is what I tried:

for name in DF['names'].unique():
    df_name = name + '_df'
    df_name = DF.loc[DF['names'] == str(name)

If one of the names in the DF['names'] column is 'George', the below command should work to print out the beginning of of of the dataframes that was generated.

George_df.head()

But I get an error message:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Previous questions discuss ways to do this in a dictionary, but I am looking for a way to implement this for a dataframe.

2 Answers

SetUp

df=pd.DataFrame({'names' : ['a','a','b','b'], 'values':list('1234')})

print(df)

  names values
0     a      1
1     a      2
2     b      3
3     b      4

Using globals and DataFrame.groupby

for name, group in df.groupby('names'):
    globals()[f'df_{name}'] = group
print(df_a)

  names values
0     a      1
1     a      2

print(df_b)

  names values
2     b      3
3     b      4

Although using globals is not recommended, I suggest you use a dictionary

dfs = dict(df.groupby('names').__iter__())
print(dfs['a'])

  names values
0     a      1
1     a      2

I would recommend going with a dictionary structure like so:

test_dict = {}
test_dict["George"] = pd.DataFrame({"A":[1,2,3,4,5]})

In your case:

test_dict = {}

for name in DF['names'].unique():
    df_name = name + '_df'
    test_dict[df_name] = DF.loc[DF['names'] == str(name)]

But if you need to set new variables, this post will explain how to create them.

for name in DF['names'].unique():
    df_name = name + '_df'
    globals()[df_name] = DF.loc[DF['names'] == str(name)]
Related