python - 如何将数据写入码头中的多索引数据框?
问题描述
我希望标头包含数组名称的值,数据取自数据帧 nev_df。我怎样才能做到这一点?但我不知道如何将多索引写入dox表中的数据框,以便标题与索引0重叠
我正在申请,因为我没有在 Internet 上找到我需要的解决方案。我是使用库 python-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')
解决方案
推荐阅读
- postgresql - pg_cron 安装:没有创建 cron 表
- python - 如何在 Jupyter 笔记本的 HTML 输出中获取垂直滚动条
- reactjs - 在两个不同的主机上部署 React + API 应用程序
- php - 正确重定向以避免 www/non-www 页面被视为重复
- prettier - 如何使用 Prettier 递归检查文件
- java - Java:如何从用户输入创建方法
- python - 如何使用Visual Studio compile读取python目录中的所有文件
- sql - Powershell 日期时间到 SQL 日期时间
- javascript - 将函数作为参数传递给递归 setTimeout
- javascript - 使用 Flask 将 JavaScript 连接到 Python 脚本