Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name dataframes in a for-loop? [duplicate]

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.

like image 525
arkadiy Avatar asked Aug 27 '26 02:08

arkadiy


1 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
like image 55
ansev Avatar answered Aug 28 '26 15:08

ansev