简体   繁体   中英

How to make a sum by using group by?

I have the following dataset and I want to sum the values of the column UnitPrice grouping by CustomerID.

在此处输入图像描述

I'm trying the following way but despite the new column is being added the values are not being filled

data['TotalEN'] = round(data.groupby(['SalesOrderID'])['UnitPrice'].sum(),2)

I tried to print the function if is calculating the values correctly and indeed it is

print(data.groupby(['CustomerID'])['UnitPrice'].sum())

在此处输入图像描述

What I'm doing wrong?

In this case, the shape of the output from the groupby operation will be different than the shape of your dataframe. You will need to use the transform method on the groupby object to restore the correct shape you need:

data['TotalEN'] = data.groupby(['SalesOrderID'])['UnitPrice'].transform('sum').round(2)

You can read more about transform here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM