Skip to content
Advertisement

Splitting Dataframe into different group by product

I am trying to split my Dataframe such that each Dataframe is for a product. Given below is how my Dataframe looks like:

row_label, jan, feb, mar, apr
prod_a, 100, 120, 123, 150
prod_b, 123, 233, 200, 40
prod_c, 10, 23, 34, 33

Expected output:

Dataframe for prod_a

row_label, value
jan, 100
feb, 120
mar, 123
apr, 150

Dataframe for prod_b

row_label, value
jan, 123
feb, 233
mar, 200
apr, 40

Dataframe for prod_c

row_label, value
jan, 10
feb, 23
mar, 34
apr, 33

Advertisement

Answer

I suggest here create dictionary of DataFrames in dictionary comprehension:

df1 = df.set_index('row_label').T

dfs = {x: df1[x].to_frame(name='value') for x in df1.columns}

print (dfs['prod_a'])

Variables from strings are not recommended, but possible, e.g. with globals:

for x in df1.columns:
    globals()[x] =  df1[x].to_frame('value')

print (prod_a)

Another idea with groupby, thank you @Lunalo John for idea:

dfs = {k: v.T for k,  v in df.set_index('row_label').groupby('row_label')}
print (dfs['prod_a'])
row_label  prod_a
jan           100
feb           120
mar           123
apr           150
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement