简体   繁体   English

Python - 遍历 excel 列值以拆分为单独的工作表

[英]Python - Iterate through excel column values to split up into separate sheets

I have an excel file with different columns, and I would like to split them up into different sheets based on unique column values (in this case, the month name. So 12 sheets would be created, one for each month. I got it working when I hardcoded it without loops, but I'd rather loop it through a list to save the time.我有一个包含不同列的 excel 文件,我想根据唯一的列值(在本例中为月份名称)将它们分成不同的工作表。因此将创建 12 个工作表,每个月一个。我让它工作当我在没有循环的情况下对其进行硬编码时,但我宁愿通过一个列表循环它以节省时间。

My current output in the excel file a sheetname called 'February' with the entire dataset.我当前在 excel 文件中的 output 文件名称为“February”,其中包含整个数据集。

Anyone have any ideas?有人有想法么? Thank you!谢谢!

import xlrd
import xlsxwriter

df = pd.read_excel(r"PATH\data_test.xlsx", index_col = 0)
#writer = pd.ExcelWriter("Test3.xlsx", engine = 'xlsxwriter')
test_list = ['January', 'February']

for i in test_list:
    writer = pd.ExcelWriter("Test3.xlsx", engine='xlsxwriter')
    df.loc[i]
    df.to_excel(writer, sheet_name = i)
    print(i)
    writer.save()

contents of df: df的内容:

Month      Amount      
January       125
January        32
February       12
March          70
April          48
May            98
June          110
July            7
August        124
September      63
October        93
November        6
December      118


something like this should work:像这样的东西应该工作:

groups = df.groupby("Month")
with pd.ExcelWriter("my_file.xls") as writer:
    for (name, df_group) in groups:
        df_group.to_excel(writer, sheet_name=name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 遍历 excel 文件和工作表并在 Python 中连接 - Iterate through excel files and sheets and concatenate in Python Python:如何在数据框中传递3列作为函数中的3个独立参数并迭代列值 - Python: how to pass 3 columns in data frame as 3 separate arguments in function and iterate through the column values 在python的Pyexcel中遍历工作表 - Iterate through sheets in Pyexcel in python 遍历2个不同的Excel工作表中的列 - iterate through columns in 2 different excel sheets 如何遍历 dataframe 行,将数据拆分为基于列的单独数据帧? - How to iterate through dataframe rows, split data to separate dataframes based on column? 使用python迭代并填充excel中的列的正确方法 - Correct way to iterate through and populate a column in excel with python 循环遍历 excel 工作表并使用 Python 将值存储在变量中 - Iterate with loop through excel sheet and store values in variables using Python 将由空格分隔的一列值拆分为python中每个值的单独列 - Split a column of values delimited by a space into separate columns for each value in python Python Pandas 将列字符串值拆分为单独的列 - Python Pandas Split Column String Values into Separate Columns Python / Pandas:将单列中的美元值拆分为单独的列 - Python / Pandas: Split Dollar Values in a Single Column to Separate Columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM