【问题标题】:Python : Split 1 Excel File into multiple Excel files by rowsPython:将 1 个 Excel 文件按行拆分为多个 Excel 文件
【发布时间】:2022-12-15 12:37:10
【问题描述】:

例如,您有 1 个 excel 文件,其中包含 10000 个数据。稍后当我们在 pycharm 或 jupiter notebook 中导入该 excel 文件时。如果我运行该文件,我将获得一个索引范围,也称为行标签。我的 python 代码应该能够读取那一万行标签,并且应该能够分离/拆分为 10 个不同的 excel 工作表文件,这些文件在 10 个分离的工作表中的每个工作表中都有 1000 个数据。 另一个例子是,如果 1 个工作表/文件中有 9999 个数据,那么我的 python 代码应该在 9 个工作表中划分 9000 个数据,在其他工作表中划分 999 个数据而不会出现任何错误。{这是重要的问题}

我问这个是因为在我的数据中,我的代码没有任何唯一值来使用 .unique 拆分文件

【问题讨论】:

标签: python excel pandas dataframe numpy


【解决方案1】:

你可以使用 Pandas 来读取你的文件,分块然后重写它:

import pandas as pd

df = pd.read_excel("/path/to/excels/file.xlsx")

n_partitions = 3

for i in range(n_partitions):
    sub_df = df.iloc[(i*n_paritions):((i+1)*n_paritions)]
    sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")

编辑: 或者,如果您更喜欢设置每个 xls 文件的行数:

import pandas as pd

df = pd.read_excel("/path/to/excels/file.xlsx")

rows_per_file = 4

n_chunks = len(df) // rows_per_file

for i in range(n_chunks):
    start = i*rows_per_file
    stop = (i+1) * rows_per_file
    sub_df = df.iloc[start:stop]
    sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")
if stop < len(df):
    sub_df = df.iloc[stop:]
    sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")

您需要openpyxl 才能读取/写入 Excel 文件

【讨论】:

  • 第一个现在可以工作了,第二个很好,它也可以在我的 9999 数据在一个单独的 excel 文件中,每个 excel 文件中有 1000 个数据的情况下工作,但问题是剩余的 999 数据没有打印在楼层部门的另一个 excel 文件是 // 我猜。
  • 最后一个条件为 if stop &lt; len(df) 的事件?这是为了处理最后的 999 行
  • 好的,嗯……
【解决方案2】:

以下代码 sn-p 对我来说工作正常

import pandas as pd
import openpyxl
import math

data =  pd.read_excel(r"path_to_excel_file.xlsx")

_row_range = 200
_block = math.ceil(len(data)/_row_range )

for x in range(_block,_row_range ):
    startRow = x*_row_range 
    endRow = (x+1)*_row_range 
    _data = data.iloc[startRow:endRow]
    _data.to_excel(f"file_name_{x}.xlsx",sheet_name="Sheet1",index=False)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多