Reputation: 25
I have a list of names (I changed them to letters) that correspond with values in a data frame column.
names = ['A','B','C','D','E','F','G','H']
I am trying to create a separate data frame for each name containing that name's associated QTY grouped by part number.
for x in names:
name_data = data[data['Name']== x]
name_dict = name_data.groupby(['Part No.']).Quantity.sum().to_dict()
df1= pd.DataFrame.from_dict(name_dict, orient = 'index',columns = ['QTY'])
As you can see from the code each time it loops it writes the new loop data over the previous loop's data in df1. How to I iterate a new data frame name each time it loops, so that I end of with 8 separate data frames?
Upvotes: 2
Views: 3108
Reputation: 23146
You could save the dataframes to a list
:
list_of_dfs = list()
for x in names:
df = data[data['Name'].eq(x)].groupby('Part No.')['Quantity'].sum().rename("QTY").to_frame()
list_of_dfs.append(df)
Upvotes: 1