【问题标题】:Iterating through dataframes?遍历数据框?
【发布时间】: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]

标签: python dataframe for-loop


【解决方案1】:
  1. 首先如果你使用
for i, df in enumerate(dflist):

然后df 变量表示来自列表dfList 的数据帧。在循环内部,如果需要,您可以使用此变量 df 访问迭代数据帧(而不是 dfList[i])。

  1. 您有两个i 变量,第二个“抑制”初始i 值。第一个 i 在外部循环中定义,第二个在内部循环中。

这样的事情可能会有所帮助:

for df in 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(df.shape[0]+1, df.shape[1])

    # add the header rows.
    for j in range(df.shape[1]):
        t.cell(0,j).text = df.columns[j]

    # add the rest of the data frame
    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])

    # save the doc
    doc.save(fr'./test1[i].docx')

【讨论】:

  • 谢谢你!你会怎么编辑代码?
  • 很难写出确切的工作代码,因为我不知道doc对象是什么,但可能会更新代码帮助
  • 谢谢先生!!
猜你喜欢
  • 2021-02-17
  • 1970-01-01
  • 2016-11-26
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多