python - 如何拆分数据框并将其存储在 Excel 文件的多个工作表中

标签 python excel pandas dataframe pandas-groupby

我有一个如下所示的数据框

import numpy as np
import pandas as pd
from numpy.random import default_rng
rng = default_rng(100)
cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                   'customer': rng.choice(list('ACD'),size=(5)),
                   'region': rng.choice(list('PQRS'),size=(5)),
                   'dumeel': rng.choice(list('QWER'),size=(5)),
                   'dumma': rng.choice((1234),size=(5)),
                   'target': rng.choice([0,1],size=(5))
})
我想做以下
a) 提取 region 的唯一组合的数据和 customer .含义 groupby .
b)将它们存储在一个excel文件的每张纸中(基于组数)
我正在尝试类似下面的东西,但应该有一些简洁的pythonic方式来做到这一点
df_list = []
grouped = cdf.groupby(['customer','region'])
for k,v in grouped:
    for i in range(len(k)):
        df = cdf[(cdf['customer']==k[i] & cdf['region']==k[i+1])]
        df_list.append(df)
我希望我的输出如下所示(显示在多个屏幕截图中)。
由于我的真实数据有 200 列和 100 万行,因此任何有效而优雅的方法都会很有帮助
enter image description here
enter image description here
enter image description here

最佳答案

使用this solution在循环中:

writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter')
    
for (cust, reg), v in cdf.groupby(['customer','region']):
    v.to_excel(writer, sheet_name=f"DATA_{cust}_{reg}")
        
    # Close the Pandas Excel writer and output the Excel file.
writer.save()

关于python - 如何拆分数据框并将其存储在 Excel 文件的多个工作表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71219701/

相关文章:

python - 如何解决这个 bash python 交互?

python - 解码通过 websocket 发送的数据

python - Pandas 在数据框列上滑动窗口

Python Datareader 证券交易所市场期权

python - RGB 浮点图像转灰度 uint8

python - 如何通过 Python 创建多个 Excel 工作表?

VBA - 使用 RefEdit 作为范围

sql-server - SSIS - 将 SQL 查询结果设置为 Excel 连接字符串的变量

python - 将数据从一个 Pandas 数据框替换为另一个

python - pandas - 基于子串出现次数的表达方法