带有动态标题的 Pandas 数据框 [英] Pandas dataframe with dynamic title
本文介绍了带有动态标题的 Pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下 dataframe
:
df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})
我想给它一个用户提供的标题,例如:title = '销量'
I want to give it a title provided by user e.g.:
title = 'The sales'
如何将 title
添加到 df
以便在发送到 Excel sheet
或 pdf
时显示为:`
How can I add the title
to the df
such that when send to Excel sheet
or pdf
it appears as:
`
{title} in this case *The sales*
A B C D E F
0 a 4 7 1 5 a
1 b 5 8 3 3 a
2 c 4 9 5 6 a
3 d 5 4 7 9 b
4 e 5 2 1 2 b
5 f 4 3 0 4 b
寻找可能的解决方案导致添加column
title
,而我想要的是添加dataframe
标题.
Searching for possible solutions leads to adding column
title
, while what I want is adding dataframe
title.
推荐答案
这是使用 xlsxwriter 作为 Pandas Excel 引擎的一种方法.使用 openpyxl 也可以实现类似的功能:
Here is one way to do it using xlsxwriter as the Pandas Excel engine. Something similar would also be possible using openpyxl:
import pandas as pd
df = pd.DataFrame({'A': list('abcdef'),
'B': [4, 5, 4, 5, 5, 4],
'C': [7, 8, 9, 4, 2, 3],
'D': [1, 3, 5, 7, 1, 0],
'E': [5, 3, 6, 9, 2, 4],
'F': list('aaabbb')})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
# Shift the dataframe down one row in the Excel file.
df.to_excel(writer, sheet_name='Sheet1', startrow=1)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Write the title to the worksheet.
title = 'The sales'
worksheet.write(0, 0, title)
writer.save()
输出:
这篇关于带有动态标题的 Pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文