excelater
excelater

Reputation: 117

Pandas Groupby Percentage of total

    df["% Sales"] = df["Jan"]/df["Q1"]
    q1_sales =  df.groupby(["City"])["Jan","Feb","Mar", "Q1"].sum()
    ql_sales.head()



                   Jan  Feb  Mar   Q1
City            
Los Angeles        44   40   54   138

Want the code to get the percentage of sales for the quarter. Want it to look like this below each month is divided by the total sales of the quarter.

                     Jan    Feb   Mar  
City            
Los Angeles          31.9%  29%  39.1% 

Upvotes: 2

Views: 98

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150805

Try div:

q1_sales[['Jan','Feb','Mar']].div(q1_sales['Q1']*0.01, axis='rows')

Output:

                   Jan        Feb        Mar
City                                        
Los Angeles  31.884058  28.985507  39.130435

Upvotes: 1

ansev
ansev

Reputation: 30930

Use:

new_df=q1_sales[q1_sales.columns.difference(['Q1'])]
new_df=(new_df.T/new_df.sum(axis=1)*100).T
print(new_df)

                   Feb        Jan        Mar
Los Angeles  28.985507  31.884058  39.130435

Upvotes: 1

Related Questions