如何将 xlsxwriter .add_table() 方法与数据帧一起使用? [英] How to use xlsxwriter .add_table() method with a dataframe?

查看:48
本文介绍了如何将 xlsxwriter .add_table() 方法与数据帧一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是数据框'我该怎么做?

import xlsxwriterworkbook = xlsxwriter.Workbook("test1.xlsx")worksheet = workbook.add_worksheet("sheli22")worksheet.add_table('B3:F7', {'data': data,'style': 'Table Style Light 17','header_row': False})workbook.close()

解决方案

根据涵盖 .add_table() 方法的 xlsxwriter 文档部分,它期望数据结构应该是一个列表列表"(

my data is dataframe ' how can i do it ?

import xlsxwriter

workbook = xlsxwriter.Workbook("test1.xlsx")
worksheet = workbook.add_worksheet("sheli22")
worksheet.add_table('B3:F7', {'data': data,'style': 'Table Style Light 17','header_row': False})

workbook.close()

解决方案

According the xlsxwriter Documentation Section covering the .add_table() method, it expects that "the data structure should be an list of lists" (link to docs).

To create this list of lists from your dataframe, it will be necessary to use .T to transpose the dataframe and then .tolist() to convert the transposed dataframe into a list of lists.

I have a fully reproducible example using a sample dataframe below.

import pandas as pd
import xlsxwriter

data = pd.DataFrame({'a':[1,2,3,4,5],
                   'b':[2,3,4,5,6],
                   'c':[3,4,5,6,7],
                   'd':[4,5,6,7,8],
                   'e':[5,6,7,8,9]})

workbook = xlsxwriter.Workbook("test1.xlsx")
worksheet = workbook.add_worksheet("sheli22")
worksheet.add_table('B3:F7', {'data': data.values.T.tolist(),'style': 'Table Style Light 17','header_row': False})

workbook.close()

With Expected Output:

这篇关于如何将 xlsxwriter .add_table() 方法与数据帧一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆