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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With