提问者:小点点

Pandas:将数据框架写入按名称分组的多个工作表


我有以下数据帧:

Receipt Description Card Member Account Cost Data
200a apple adam 08203928 $2 need more apples
200a apple adam 08203928 $2 need more apples
20022a pear bob 3214 $7
202a orange alice 411423432 $8
202a orange alice 321321 $8
202a orange alice 3213121 $8

我已按“卡成员”列对我的数据帧进行了排序。

我希望能够使用此数据创建多个新的excel工作表,每个工作表按名称分组,就像我当前所做的那样。

例如:

在“Adam”,“Alice”和“Alice”上方的数据帧中 “Bob”每个人都有自己的表单,其中只包含这些数据,而不包含任何其他数据。


共1个答案

匿名用户

您可以尝试以下操作:

创建Excel工作表时需要安装的XLSXWriter引擎。

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter(r"sample.xlsx", engine='xlsxwriter')

分组,并将每个数据帧保存在单独的工作表中。

for index, group_df in df.groupby("Card"):   
    group_df.to_excel(writer, sheet_name=str(index),index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.save()