我是新来的大熊猫和python-DOCX,在熊猫使用GROUPBY像这样的表:
在使用print(df)
打印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