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?

1
  • Maybe you could append instead of concat them like this answer - stackoverflow.com/questions/36526282/… and just append each dataframe after each iteration? Commented Dec 14, 2021 at 18:46

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.