熊猫 - 按列值将数据帧拆分为多个 Excel 工作簿



我是熊猫的新手。我有一个大的 excel 文件,我正在尝试做的是在操作后将数据框拆分为多个 excel 工作簿。或多或少有 400 家供应商,我希望每个供应商都有自己的命名工作簿。

例。SallyCreative.xlsx, JohnWorks.xlsx, AlexGraphics.xlsx

尝试下面的代码,希望它会有所帮助并为您提供所需的解决方案。

考虑我有这样的数据。

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/

希望会有所帮助

这是我按列值将数据帧拆分为多个 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. 

最新更新