Pandas percentage of total with groupby

前端 未结 14 2259
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 06:41

This is obviously simple, but as a numpy newbe I\'m getting stuck.

I have a CSV file that contains 3 columns, the State, the Office ID, and the Sales for that office

14条回答
  •  既然无缘
    2020-11-22 06:56

    One-line solution:

    df.join(
        df.groupby('state').agg(state_total=('sales', 'sum')),
        on='state'
    ).eval('sales / state_total')
    

    This returns a Series of per-office ratios -- can be used on it's own or assigned to the original Dataframe.

提交回复
热议问题