How to Create Multiple Data Frames Using a for Loop in Python

how to create multiple data frames from another dataframe in a loop

Create a dict with 3 entries where the key is the period and the value is the corresponding subset dataframe:

dfs = dict(list(df.groupby('period')))
>>> dfs[1167]
id period
0 1 1167
1 2 1167

>>> dfs[1168]
id period
2 3 1168
3 4 1168

>>> dfs[1169]
id period
4 5 1169
5 6 1169

Don't use this

If you really want to create 3 variables df1167, df1168 and df1169 that can be direct accessible by their name:

for period, subdf in df.groupby('period'):
locals()[f'df_{period}'] = subdf
>>> df_1167
id period
0 1 1167
1 2 1167

>>> df_1168
id period
2 3 1168
3 4 1168

>>> df_1169
id period
4 5 1169
5 6 1169

How do I create multiple data frames using a for loop in python

If I understand correctly, you can use a list comprehension for this:

subset_df_list = [df.groupby('Location').get_group(36) for df in df_list]

As an aside, your for loop doesn't work because you just keep assigning back to df. You probably want this, which is also the equivalent of the above comprehension:

subset_df_list = []

for df in df_list:
subset_df = df.groupby('Location').get_group(36)
subset_df_list.append(subset_df)


Related Topics



Leave a reply



Submit