【发布时间】:2022-01-12 07:14:36
【问题描述】:
dflist = [DP, SMP, SMD, MP, MD, MSM, SAP, SAD,SAMA, SAM, AP,AD, ASM, AM,ASA]
for i, df in enumerate(dflist):
# open an existing document
doc = docx.Document()
# add a table to the end and create a reference variable
# extra row is so we can add the header row
t = doc.add_table(dflist[i].shape[0]+1, dflist[i].shape[1])
# add the header rows.
for j in range(dflist[i].shape[-1]):
t.cell(0,j).text = dflist[i].columns[j]
# add the rest of the data frame
for i in range(dflist[i].shape[0]):
for j in range(dflist[i].shape[-1]):
t.cell(i+1,j).text = str(dflist[i].values[i,j])
# save the doc
doc.save(fr'./test1[i].docx')
我正在尝试遍历数据框列表,以便为每个数据框创建一个 word 文档。
但是,我收到以下错误;
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-18-d61049a379a0> in <module>
14 for i in range(dflist[i].shape[0]):
15 for j in range(dflist[i].shape[-1]):
---> 16 t.cell(i+1,j).text = str(dflist[i].values[i,j])
17
18 # save the doc
IndexError: index 0 is out of bounds for axis 0 with size 0
上面的代码你会怎么写?
【问题讨论】:
-
您的
DataFrame之一似乎是空的? -
既然有
df可用,为什么还要使用dflist[i]?