【问题标题】:Using Python And Pandas To Split Excel Worksheet Into Separate Worksheets使用 Python 和 Pandas 将 Excel 工作表拆分为单独的工作表
【发布时间】:2019-05-30 03:08:01
【问题描述】:

我需要一个脚本来将主工作表(包含超过 50K 行)拆分为单独的工作表,其中仅包含 40 行且没有标题

经过一番研究,我设法创建了一个拆分主工作表的脚本。但是,每个工作表都包含原始标题,并且行不会被拆分为每个工作表的 40 行。

我相信当您使用带有数据框的 panda 拆分工作表时,它们将始终包含一个标题?关于如何修改我的 python 脚本以实现我需要的任何建议,或者有没有更简单的方法来实现这一点而无需使用 pandas 和数据框?

这里是一些示例数据的链接:https://github.com/lblake/sample-data

path = input('Enter file path to workbook name and extension, 
e.g. example.xlsx: ')
chunksize = int (input('Enter the row number you want to split the excel sheet at: ') )
destination = input('Enter folder path to where you want the split files stored. Press Enter to save in current location: ')

i = 0
df = pd.read_excel(path)
for chunk in np.array_split(df, len(df) // chunksize):
    chunk.to_excel(destination + 
'file_{:02d}.xlsx'.format(i), index=True)
i += 1 

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用groupby 并进行迭代。要忽略标头,请在写入 pd.ExcelWriter 对象时指定 header=False。下面的示例将 10 行的数据帧拆分为 2 行块。

    df = pd.DataFrame(np.arange(100).reshape((10, 10)))
    
    writer = pd.ExcelWriter('file.xlsx')
    
    for key, grp in df.groupby(df.index // 2):
        grp.to_excel(writer, f'sheet_{key}', header=False)
    
    writer.save()
    

    【讨论】:

      【解决方案2】:

      我刚刚复制了你的代码并添加了header=False

      path = input('Enter file path to workbook name and extension, 
      e.g. example.xlsx: ')
      chunksize = int (input('Enter the row number you want to split the excel sheet at: ') )
      destination = input('Enter folder path to where you want the split files stored. Press Enter to save in current location: ')
      
      i = 0
      df = pd.read_excel(path)
      for chunk in np.array_split(df, len(df) // chunksize):
          chunk.to_excel(destination + 
      'file_{:02d}.xlsx'.format(i), index=True, header=False)
      i += 1 
      

      它对我有用。

      【讨论】:

      • 感谢在我的代码中添加 header=False 选项解决了我的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      相关资源
      最近更新 更多