【问题标题】:Group specific rows from multiple files and save each groups of rows in a new excel file with python (pandas, openpyxl)将多个文件中的特定行分组,并使用 python(pandas、openpyxl)将每组行保存在新的 excel 文件中
【发布时间】:2023-01-10 01:22:46
【问题描述】:

有人可以帮我解决以下问题:

  • 我有多个 excel 文件,其中一些有 3 列('Year'、'Car'、'Price'),其他有 5 列('Year'、'Car'、'Color'、'Places'、'Country') ;

  • 在每个文件的特定列(“年份”)中,我想按年份对行进行分组;

  • 然后我想将这些行组保存在一个新文件的不同工作表中。

我的实际问题是,当 python 从这些文件中读取行并将行分组时,我的代码只会将最后一个文件保存为红色。

非常感谢!

from tkinter import filedialog
import pandas as pd

window = Tk()
window.title("title")
#(etc.)
label .pack()

def action():
     all_files = filedialog.askopenfilename(initialdir = "/", 
     multiple=True,
     title="select",
     filetypes=(
             ("all files", "*.*"),
             ("Excel", "*.xlsx*")))
      dossier=filedialog.askdirectory()
      final=pd.DataFrame()
      first=True
      for f in all_files:
           step1 =pd.read_excel(f,sheet_name=0)
           final=step1
           final['Year']=final['Year'].apply(str)
           lst1=final.groupby('Year')
           lst0=lst1.get_group('2013')
           with pd.ExcelWriter(dossier+'\\sells.xlsx') as writer:
                lst0.to_excel(writer, sheet_name='2013',index=False)
    tkinter.messagebox.showinfo("Files", "Ready")

【问题讨论】:

    标签: python pandas database openpyxl


    【解决方案1】:

    ExcelWriter 将默认模式设置为写入:

    mode{‘w’, ‘a’}, 默认‘w’要使用的文件模式(写入或追加)。 Append 不适用于 fsspec URL。

    尝试将 if_sheet_exists 设置为 overlay 来指定追加模式:

    if_sheet_exists{‘error’, ‘new’, ‘replace’, ‘overlay’}, 默认‘error’
    尝试写入已存在的工作表时的行为方式(仅限追加模式)。

    • 错误:引发 ValueError。
    • new:创建一个新的工作表,名称由引擎决定。
    • 替换:在写入之前删除工作表的内容。
    • 覆盖:将内容写入现有工作表而不删除旧内容。
    with pd.ExcelWriter(dossier+'\sells.xlsx', mode="a", if_sheet_exists="overlay") as writer:
       # ...
    

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2022-10-14
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多