Home > database >  Create multiple dfs from a single df
Create multiple dfs from a single df

Time:09-21

I have a df as:

Company Sales
A        100
A        200
A        300
B        50
B        60
C        10
C        20

Now I want to make separate dfs for each of the company such that one df only contains info on one company as below:

Company   Sales
A        100
A        200
A        300

Similarly, for B as -

Company   Sales
B        50
B        60

CodePudding user response:

You can use groupby and transform to dictionary:

dfs = dict(list(df.groupby('Company')))

then you can access the sub-dataframes by key:

>>> dfs['A']
  Company  Sales
0       A    100
1       A    200
2       A    300

how to do something with the dataframes programmatically:

for company, data in df.groupby('Company'):
    emailing_function(company, data)

or:

companies = df['Company'].unique()
dfs = dict(list(df.groupby('Company')))

### other part of code
for company in companies:
    emailing_function(company, dfs[company])

CodePudding user response:

We can use groupby in Pandas and save individual dataframe in excel (or any other format). Here is the working code.

df_grp = df.groupby('Company')

for comp_nam, comp_grp in df_grp:
    file_name = comp_nam.upper() ".xlsx"
    comp_grp.to_excel(file_name, index=False)
  • Related