设置 pandas DataFrame 的索引时,列数组的最后一个元素不会将项目合并/分组在一起。
假设有以下测试数据:
test_data = {
"desk": ["DESK1", "DESK2", "DESK3", "DESK4", "DESK5", "DESK6", "DESK7", "DESK8", "DESK9", "DESK10"],
"phone": ["111-1111", "111-1111", "111-1111", "111-1111", "444-4444", "444-4444", "111-1111", "111-1111", "123-4567", "123-4567"],
"email": ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"],
"team1": ["Adam", "xxxx", "Tiana", "", "Gina", "Gina", "Ruby", "Becca", "John", ""],
"team2": ["", "", "Dime", "", "Ed", "", "", "", "Fa", "Tim"],
}
创建了一个数据框:
import io
import pandas as pd
from django.http.response import HttpResponse
from rest_framework import status
### Create DataFrame from test_data
df = pd.DataFrame(test_data)
然后尝试写入并返回文件
### Write & return the file
with io.BytesIO() as buffer:
with pd.ExcelWriter(buffer) as writer:
df: pd.DataFrame = df
groupby_columns = ['desk', 'phone', 'email']
df.set_index(groupby_columns, inplace=True, drop=True, append=False )
df.to_excel(writer, index=True, sheet_name="Team Matrix", merge_cells=True)
return HttpReponse(
buffer.getvalue(),
headers={
"Content-Type": "application/vnd.openxmlformats-" "officedocument.spreadsheetml.sheet",
"Content-Disposition": "attachment; filename=excel-export.xlsx",
},
status=status.HTTP_201_CREATED,
)
返回以下文件: 返回的 Excel 文件
但我想要的是,如果数据相同,则前三列(办公桌、电话、电子邮件)将被合并,使用上面的代码,它会对办公桌和电话列进行合并,但电话列不会像其他两列那样分组/合并。 所需返回的 Excel 文件
一种可能的解决方案是,将空 (
""
) 值放入所需的单元格中,然后合并单元格:这将创建一个带有空单元格的新数据框:
印刷:
此步骤将合并 Excel 中的前 3 列:
创建
out.xlsx
(来自 LibreOffice 的屏幕截图):