简体   繁体   中英

How could I write a function or loop that assigns each unique value into its own accessible dataframe?

I am looking for a way to create a dataframe for each unique value in a column of a dataframe.

I have a table like the following (obviously this is made up data):

| Staff |  debit  |  credit  | Day      |
| Bob   |  100    |  25      | Monday   |
| Sue   |  15     |  95      | Wednesday|
| Bob   |  125    |  40      | Monday   |
| Bob   |  100    |  2       | Friday   |
| Sue   |  50     |  50      | Tuesday  |
| Bob   |  16     |  80      | Thursday |

I have created a dataframe dictionary that filters the way that I would like to using this code:

x = dict(tuple(report.gropuby('Staff')))

Then I can call each key to print the filtered dataframe by:

Bob = x['Bob']

Which will look something like:

| Staff |  debit  |  credit  | Day      |
| Bob   |  100    |  25      | Monday   |
| Bob   |  125    |  40      | Monday   |
| Bob   |  100    |  2       | Friday   |
| Bob   |  16     |  80      | Thursday |

Is there a way that I can loop for each key in the dictionary to name and create a dataframe for each key from this dataframe dictionary? Then I would like to export each of the dataframes to its own Excel sheet (.xls or .xlsx) of the same Excel file. There are over 50 staff and it changes each fairly regularly so it would be nice to automate this rather than manually writing a list of names each time.

I figured a different approach that does what I wanted to do, maybe it will help someone else. Instead of creating that dictionary and then trying to convert it to Excel, I instead converted into Excel using groupby from the original dataframe using the following code:

 with pd.ExcelWriter('test.xlsx') as writer: 
    for Staff, df in  df.groupby('Staff'): 
        df.to_excel(writer, sheet_name = Staff)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM