python - 如何将 groupby 分组表从 dataFrame 写入 word 文档?
问题描述
我是 pandas 和 python-docx 的新手,在 pandas 中使用 groupby 有一个这样的表:
在使用打印 dfprint(df)
输出:
Change Type typeA typeB typeC typeD typeE typeF
Component
A 0 2 6 0 0 6
B 0 3 2 1 1 3
C 0 1 0 0 0 4
D 0 2 2 0 0 3
E 0 0 0 0 0 1
F 0 3 0 0 1 2
G 2 1 3 0 2 3
H 0 0 0 0 0 1
I 0 1 0 0 0 0
我正在使用以下内容将此数据帧df
写入word document
:
t = doc.add_table(df.shape[0]+1, df.shape[1])
for j in range(df.shape[-1]):
t.cell(0,j).text = df.columns[j]
for i in range(df.shape[0]):
for j in range(df.shape[-1]):
t.cell(i+1,j).text = str(df.values[i,j])
如答案中所述:
Writing a Python Pandas DataFrame to Word document
我正在打印以下内容:
typeA typeB typeC typeD typeE typeF
0 2 6 0 0 6
0 3 2 1 1 3
0 1 0 0 0 4
0 2 2 0 0 3
0 0 0 0 0 1
0 3 0 0 1 2
2 1 3 0 2 3
0 0 0 0 0 1
0 1 0 0 0 0
我是新手,因此无法弄清楚我哪里出错了,我想打印整个表格?
解决方案
看起来您没有将数据框的index
值写入文件。我已经修改了您的脚本,以显示您可以使用df.index
它们来访问这些内容,然后将它们写入第一列。
#...
t = doc.add_table(df.shape[0]+2, df.shape[1]+1) #df.shape[1]+1 to add one extra column for row names
for j in range(df.shape[-1]):
t.cell(0,j+1).text = df.columns[j]
for i in range(df.shape[0]):
for j in range(df.shape[-1]):
t.cell(i+2,j+1).text = str(df.values[i,j])
# write columns name to file
t.cell(0,0).text = df.columns.name
# write the index values to file
t.cell(1,0).text = df.index.name
for i, my_index in enumerate(df.index):
t.cell(i+2,0).text = my_index
推荐阅读
- excel - 将功能添加到 Excel,而不是通过加载项
- c# - 如何使用 Hooks 唯一标识应用程序中的字段或控件?
- php - PHP数组与数组(二维数组?)到csv
- javascript - 如何在 ESLint 中使用平面嵌套三元组?
- android - ViewPager 图像视图在回收站视图中的随机项目位置显示 null
- ruby-on-rails - Rails 本地化:以扁平的非嵌套方式排列 i18n yml 文本有什么缺点吗?
- firebase - admin sdk 的 firebase 实时数据库规则
- vuetify.js - 深色主题不适用于所有子组件
- html - 从 CSS 关闭汉堡菜单
- php - php中多维数组的唯一数组