Pandas DataFrame 到 Excel:索引的垂直对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41364380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame to Excel: Vertical Alignment of Index
提问by Dance Party2
Given the following data frame: import pandas as pd
给定以下数据框:import pandas as pd
d=pd.DataFrame({'a':['a','a','b','b'],
'b':['a','b','c','d'],
'c':[1,2,3,4]})
d=d.groupby(['a','b']).sum()
d
I'd like to export this with the same alignment with respect to the index (see how the left-most column is centered vertically?). The rub is that when exporting this to Excel, the left column is aligned to the top of each cell:
我想以与索引相同的对齐方式导出它(看看最左边的列如何垂直居中?)。问题在于,将其导出到 Excel 时,左列与每个单元格的顶部对齐:
writer = pd.ExcelWriter('pandas_out.xlsx', engine='xlsxwriter')
workbook = writer.book
f=workbook.add_format({'align': 'vcenter'})
d.to_excel(writer, sheet_name='Sheet1')
writer.save()
...produces...
...产生...
Is there any way to center column A vertically via XLSX Writer or another library?
有没有办法通过 XLSX Writer 或其他库垂直居中 A 列?
Thanks in advance!
提前致谢!
回答by Shijo
You are trying to change the formatting of the header so you should first reset the default header settings
您正在尝试更改标题的格式,因此您应该首先重置默认标题设置
pd.core.format.header_style = None
Then apply the formatting as required
然后根据需要应用格式
format = workbook.add_format()
format.set_align('center')
format.set_align('vcenter')
worksheet.set_column('A:C',5, format)
here is complete working code
这是完整的工作代码
d=pd.DataFrame({'a':['a','a','b','b'],
'b':['a','b','c','d'],
'c':[1,2,3,4]})
d=d.groupby(['a','b']).sum()
pd.core.format.header_style = None
writer = pd.ExcelWriter('pandas_out.xlsx', engine='xlsxwriter')
workbook = writer.book
d.to_excel(writer, sheet_name='Sheet1')
worksheet = writer.sheets['Sheet1']
format = workbook.add_format()
format.set_align('center')
format.set_align('vcenter')
worksheet.set_column('A:C',5, format)
writer.save()