簡體   English   中英

將多個文件中的特定行分組,並將每組行保存在一個新的 excel 文件中,其中包含 python(pandas,openpyxl)

[英]Group specific rows from multiple files and save each groups of rows in a new excel file with python (pandas, openpyxl)

有人可以幫我解決以下問題:

  • 我有多個 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")

ExcelWriter的默認模式設置為寫入:

mode{'w', 'a'}, 默認 'w'要使用的文件模式(寫入或追加)。 Append 不適用於 fsspec URL。

嘗試指定 append 模式並將if_sheet_exists設置為overlay

if_sheet_exists{'error', 'new', 'replace', 'overlay'}, 默認 'error'
嘗試寫入已存在的工作表時的行為方式(僅限追加模式)。

  • 錯誤:引發 ValueError。
  • new:創建一個新的sheet,名字由引擎決定。
  • replace:在寫入之前刪除工作表的內容。
  • 覆蓋:將內容寫入現有工作表而不刪除舊內容。
with pd.ExcelWriter(dossier+'\\sells.xlsx', mode="a", if_sheet_exists="overlay") as writer:
   # ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM