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')
I am trying to iterate through the list of dataframes so that I create a word document for each of them.
However, I am getting the following error;
---------------------------------------------------------------------------
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
How would you write the above code?
for i, df in enumerate(dflist):
then df
variable represents dataframe from the list dfList
. And inside the loop you can use this variable df
if needed access iterated dataframe (instead of dfList[i]
).
i
variables, and second one "suppress" the value of initial i
value. First i
defined in outer loop, and second in inner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.