首页 > 解决方案 > 如何将数据写入码头中的多索引数据框?

问题描述

我希望标头包含数组名称的值,数据取自数据帧 nev_df。我怎样才能做到这一点?但我不知道如何将多索引写入dox表中的数据框,以便标题与索引0重叠

我正在申请,因为我没有在 Internet 上找到我需要的解决方案。我是使用库 python-docx 的新手

正确输入: 正确输入

这是我的代码在 docx 中写的: 输入错误

我的代码:

names = ['Factor','Year','World Value']    
doc = {6: {2016: 0.6609381349660216, 2017: 0.6623539667069717, 2018: 0.6705004539991144, 2019: 0.6470456380505956, 2007: 0.5520814602571774, 2008: 0.6883677306864346, 2009: 0.6567919876164886, 2010: 0.6341924825418297, 2011: 0.6723468700662476, 2012: 0.6750988605150847, 2013: 0.6434239077958611, 2014: 0.6977729348945159, 2015: 0.6643959547744175}})
    
doc = pd.DataFrame(doc)
index = pd.MultiIndex.from_frame(doc)
new_df = pd.DataFrame(doc.unstack())

# pandas data frame
saves_d = docx.Document()
saves_d.save('./test.docx')

# open an existing document
docum = docx.Document('./test.docx')


# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = docum.add_table(new_df.shape[0]+1, new_df.shape[1])

# add the header rows.
for j in range(new_df.shape[-1]):
    t.cell(0,j).text = str(new_df.columns[j])
# add the rest of the data frame
for i in range(new_df.shape[0]):
    for j in range(new_df.shape[1]):
        t.cell(i+1,j).text = str(new_df.values[i,j-1])


# save the doc
docum.save('./test.docx')

标签: pythonpandaspython-2.7python-docx

解决方案


推荐阅读