[英]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')))
x = dict(tuple(report.gropuby('Staff')))
Then I can call each key to print the filtered dataframe by:然后我可以通过以下方式调用每个键来打印过滤后的数据帧:
Bob = x['Bob']
鲍勃 = x['鲍勃']
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.
然后我想将每个数据框导出到同一个 Excel 文件的自己的 Excel 工作表(.xls 或 .xlsx)。 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.
有超过 50 名员工,而且每个人都定期更换,因此最好自动执行此操作,而不是每次手动编写姓名列表。
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:
我没有创建该字典然后尝试将其转换为 Excel,而是使用以下代码从原始数据帧中使用 groupby 转换为 Excel:
with pd.ExcelWriter('test.xlsx') as writer:
for Staff, df in df.groupby('Staff'):
df.to_excel(writer, sheet_name = Staff)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.