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
Regex That Matches a Number With Commas for Every Three Digits
How to Delete a Column That Contains Only Zeros in Pandas
What Is the Most Efficient Way to Sum a Dict With Multiple Keys by One Key
Calculating Manhattan Distance in Python in an 8-Puzzle Game
Checking If a Pair of Value Is Inside a 2D Array Python
How to Retrieve Data from Dynamic Table - Selenium Python
Search and Replace a Line in a File in Python
How to Calculate Rolling/Moving Average Using Python + Numpy/Scipy
Index 0 Is Out of Bounds for Axis 0 With Size 0
Pandas.Read_Excel Parameter "Sheet_Name" Not Working
What Causes a Python Segmentation Fault
Convert HTML String to an Image in Python
How to Change a Dataframe Column from String Type to Double Type in Pyspark
How to Copy a File to a Remote Server in Python Using Scp or Ssh
How to Send Keys to a Game I Am Playing,Using Python