[英]Iterating through dataframes?
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.我正在尝试遍历数据框列表,以便为每个数据框创建一个 word 文档。
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
.然后
df
变量代表 dfList 列表中的dfList
。 And inside the loop you can use this variable df
if needed access iterated dataframe (instead of dfList[i]
).在循环内部,如果需要,您可以使用此变量
df
访问迭代的 dataframe (而不是dfList[i]
)。
i
variables, and second one "suppress" the value of initial i
value.i
变量,第二个“抑制”初始i
值的值。 First i
defined in outer loop, and second in inner.i
在外循环中定义,然后在内部循环中定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.