2

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?

Drake
  • 25
  • 1
  • 4
  • Maybe you could append instead of concat them like this answer - https://stackoverflow.com/questions/36526282/append-multiple-pandas-data-frames-at-once and just append each dataframe after each iteration? – Jacob Dec 14 '21 at 18:46

1 Answers1

1

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)
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • Thanks for the help. I gave it a shot, but had a few problems. I was hoping to put the data in data frames so that I could add more columns of information to the data as I go. Can I do this once it is a list, or can I then convert the QTY data in the list back to data frames? – Drake Dec 14 '21 at 20:09
  • This is a list of dataframes. So if you do `list_of_dfs[0]`, that would give you a DataFrame. You can do whatever you need with that. – not_speshal Dec 14 '21 at 20:22