簡體   English   中英

Pandas - 按列值將數據框拆分為多個 Excel 工作簿

[英]Pandas - Splitting dataframe into multiple excel workbooks by column value

我是熊貓的新手。 我有一個很大的 excel 文件,我想要做的是將操作后的數據框拆分為多個 excel 工作簿。 大約有 400 個供應商,我希望每個供應商都有自己的命名工作簿。

例子。 SallyCreative.xlsx、JohnWorks.xlsx、AlexGraphics.xlsx

這是我按列值將數據框拆分為多個 excel 工作簿的方法。

import pandas as pd
    
data = pd.read_excel('anyexcelfile.xlsx', engine='openpyxl') # creates a dataframe called 'data'; pick any spreadsheet you can add paths to 'x:/folder/subfolder/anyexcelfile.xlsx' to be explict. 

grouped = data.groupby("Column Header Name") # change "Column Header Name" to the name of the column needed to categorise or group the rows in the dataframe, 

keys = grouped.groups.keys() #create a dictionary list of the each group unique varibles in the specifed column of the dataframe.   

print(keys) #a cheeky debug to check it's working

for key in keys: #looping through each key 
        splitdf = grouped.get_group(key) # creating a temporary dataframe with only the values of the current key. 
        splitdf.to_excel(str(key)+".xlsx", engine='xlsxwriter') #write the temporary dataframe called 'splitdf' to an excel file named after the key. At the end of the loop the temporary dataframe 'splitdf' is overwritten for use with the next key. 

試試下面的代碼,我希望它會有所幫助並為您提供所需的解決方案。

考慮我有這樣的數據。

    displayName self    created id  field   fromString
0          A    A   2018-12-18  1   status  Backlog
1          B    B   2018-12-18  2   status  Funnel

現在我想創建不同的 excel 顯示名稱作為 A.xlsx 和 B.xlsx。 我們這樣做如下所示:

import pandas as pd
data_df = pd.read_excel('./data_1.xlsx')
grouped_df = data_df.groupby('displayName')

for data in grouped_df.displayName:
    grouped_df.get_group(data[0]).to_excel(data[0]+".xlsx")

在這種情況下,這將根據顯示名稱的數量為您生成 excel。 但是您可以根據需要修改解決方案。 希望這會有所幫助。

正如@Kpittman 在評論中所問的那樣

我們可以通過提供該目錄的路徑來保存在任何目錄中。

import pandas as pd
data_df = pd.read_excel('./data_1.xlsx')
grouped_df = data_df.groupby('displayName')

for data in grouped_df.displayName:
    grouped_df.get_group(data[0]).to_excel("./IO/Files/"+data[0]+".xlsx")

因此,您可以提供自定義路徑,而不是此路徑./IO/Files/

希望它會有所幫助

暫無
暫無

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

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