python - 使用 Python 和 Pandas 将 Excel 工作表拆分为单独的工作表
问题描述
我需要一个脚本来将主工作表(包含超过 50K 行)拆分为单独的工作表,这些工作表仅包含 40 行且没有标题
经过一番研究,我设法创建了一个拆分主工作表的脚本。但是,每个工作表都包含原始标题,并且行不会拆分为每个工作表 40 行。
我相信,当您使用带有数据框的熊猫拆分工作表时,它们将始终包含标题?关于如何修改我的 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
解决方案
您可以使用groupby
和迭代。要忽略标头,header=False
请在写入pd.ExcelWriter
对象时指定。下面的示例将 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()
推荐阅读
- python - Python 递归问题 (Leetcode 542)
- python - 如何从二维张量流数组中检索特定元素?
- swift - 如何将通用类型 SignedNumeric 转换为 Float?
- node.js - 无法使用 React 和 Node.js 通过 Axios 和 Nodemailer 发送发布请求 - 处于开发模式
- python - XML:删除与父节点同名的子节点
- android - 为什么在 ubuntu 中运行 Android Virtual Device 如此滞后?
- c++ - 您如何允许逗号用于基于整数的输入 c++ 的用户输入?
- excel - 关闭源文件时,无法在 for 循环中重用内容
- java - before 方法中的给定方法运行两次。为第一个捕获 null 并为第二次捕获字符串参数
- javascript - 如何在 VS Code 中禁用自动换行符?