【问题标题】:How can I duplicate every row in an excel file using Python?如何使用 Python 复制 excel 文件中的每一行?
【发布时间】:2021-01-11 01:45:21
【问题描述】:

我有一个包含如下行的 excel 文件:

col1 | col2 | col3 | col4 | col5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5

我需要复制每一行,使其看起来像这样:

col1 | col2 | col3 | col4 | col5
col1 | col2 | col3 | col4 | col5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5

这是我目前所拥有的,excel 文件是 .XLS 文件而不是 .XLSX 文件,所以我不能使用 openpyxl,除非有办法解决。

这是我目前所拥有的:

    def DuplicateEachRow(self):
        import pandas as pd
        import pathlib
        full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
        df = pd.read_excel(full_path, header=None, sheet_name=None)

        # engine can be openpyxl if we need .xlsx ext
        writer = pd.ExcelWriter(new_loc, engine='xlwt') 
        for key in df:
            sheet = df[key]
            sheet.to_excel(writer, key, index=False, header=False)
            print(sheet)
        # writer.save()

如何使用 dataframe 的“工作表”复制每一行?

编辑:我也试过这个......

    def DuplicateEachRow(self):
        import pandas as pd
        import pathlib
        full_path = str(pathlib.Path().absolute()) + '\\' + new_loc

        df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
        print(df)

        # duplicate the rows:
        dup_df = pd.concat([df, df], ignore_index=True)

        # using openpyxl
        with pd.ExcelWriter('path_to_file.xlsx') as writer:
            dup_df.to_excel(writer)

但这只会写回一张纸而不是原始工作簿

【问题讨论】:

    标签: python python-3.x excel pandas openpyxl


    【解决方案1】:

    编辑:

    此选项将根据索引号打开工作簿,读取数据,将行加倍,然后将加倍的行重写到您调用的工作表中,如果您不能使用它,请避免使用 openpyxl。至于没有找到iloc,我不确定为什么会发生这种情况,它是 pandas 包的一个组件。也许尝试将熊猫重新安装到最新版本,但我已经成功了。

    from xlrd import open_workbook
    from xlutils.copy import copy
    import pandas as pd 
    
    
    df = pd.read_excel('yourxls.xls',sheet_name='your_sheet',header=None) 
    df_new = pd.DataFrame()
    
    for i in range(len(df)):
        df_new = df_new.append(df.iloc[i])
        df_new = df_new.append(df.iloc[i])
    
    rb = open_workbook("yourxls.xls")
    wb = copy(rb)
    s = wb.get_sheet(1) #get sheet by index number
    
    num_col = len(df_new.columns)
    num_row = len(df_new)
    
    df_vals = df_new.values
    
    for i in range(num_row):
        for j in range(num_col):
            s.write(i,j, df_vals[i,j])
    
    wb.save('yourxls.xls')
    

    我必须 pip install 'xlrd''xlwt' 才能使用 .xls 格式

    【讨论】:

    • 如何对一张特定的工作表执行此操作?
    • 它说 iloc 没有定义
    【解决方案2】:

    复制数据帧中的行的一种方法是将数据帧与其自身连接:

    pd.concat([df, df])
    

    如果你想重置索引

    pd.concat([df, df], ignore_index=True)
    

    你的例子:

    def DuplicateEachRow(self):
            import pandas as pd
            import pathlib
            full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
    
            ##This should give you the dataframe for which you want to   duplicate the rows 
            ##You should check this is the case, I don't have your .xls file. 
            ##Sometimes the sheet name is "Sheet1" and not None)
            df = pd.read_excel(full_path, header=None, sheet_name=None)
            
            #duplicate the rows:
            dup_df = pd.concat([df, df], ignore_index=True)  
             
            #using openpyxl
            with pd.ExcelWriter('path_to_file.xlsx') as writer:
                 dup_df.to_excel(writer) 
    

    编辑:新版本在原始行之后插入每个重复的行并将新工作表附加到同一文件

    def DuplicateEachRow():
        import pandas as pd
        import pathlib
        full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
    
        df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
        print(df)
    
        # duplicate the rows:
        # keep the index, so you can sort the rows after
        dup_df = pd.concat([df, df])
        #sort the rows by the index so you have the duplicate one just after the initial one
        dup_df.sort_index(inplace=True)
    
        # using openpyxl
        #open the file in append mode 
        with pd.ExcelWriter(new_loc, mode='a') as writer:
            #use a new name for the new sheet
            #don't save the header (dataframe columns names) and index (dataframe row names) in the new sheet  
            dup_df.to_excel(writer, sheet_name='Sheet3', header=None, index=None)
    

    【讨论】:

    • 如何在我的示例中使用它?
    • 运行时出现此错误TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
    • 实际上我是通过更改工作表名称得到的,但文件现在看起来格式不同
    • df 长什么样子?
    • 当我打印 df 时,它正确显示了我的 excel。我会用我对您的代码所做的更改来更新我的问题
    【解决方案3】:

    最好的方法是直接使用 openpyxl 执行此操作:从工作表底部开始,插入一行并从其上方的行中复制值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2021-04-08
      • 2020-06-02
      • 2020-12-27
      • 2021-12-25
      • 2021-03-16
      相关资源
      最近更新 更多