0

Hi I have a dataset like below

df = pd.DataFrame({"price" :[250,200,100,400,200,110], "segment": ["A","A","C","B","C","B"]})

I want to know how much percentage does each segment spent. like

A = 35.71%
B = 40.47%
C = 23.82%

I have done through subsetting each segment and then doing percentage of each, but I want to do it in single line.

Thanks in advance.

  • 2
    Does this answer your question? [Get statistics for each group (such as count, mean, etc) using pandas GroupBy?](https://stackoverflow.com/questions/19384532/get-statistics-for-each-group-such-as-count-mean-etc-using-pandas-groupby) – Bill Huang Oct 25 '20 at 21:19
  • @BillHuangThis one only gives counts, I need percentage of the each segment spent value. – Praveen Bushipaka Oct 25 '20 at 21:25

1 Answers1

1

May be you can try with groupby and applying lambda to each group. Something like:

  1. first apply groupby 'segment'
  2. then for each group take the segment sum multiplied by 100
  3. and divide by total sum of df

As below:

df.groupby('segment')['price'].apply(lambda g: sum(g)*100.0/df.price.sum())

Result:

segment
A    35.714286
B    40.476190
C    23.809524
Name: price, dtype: float64
niraj
  • 17,498
  • 4
  • 33
  • 48