I cannot figure out how to combine rows with the same productcode together to sum their total order values (quantityordered * priceeach). For example:
orderdetails_df
Out[24]:
ordernumber productcode quantityordered priceeach orderlinenumber
0 10100 S18_1749 30 171.70 3
1 10100 S18_2248 50 67.80 2
2 10100 S18_4409 22 86.51 4
3 10100 S24_3969 49 34.47 1
4 10101 S18_2325 25 151.28 4
... ... ... ... ...
2991 10425 S24_2300 49 112.46 9
2992 10425 S24_2840 31 33.24 5
2993 10425 S32_1268 41 86.68 11
2994 10425 S32_2509 11 43.83 6
2995 10425 S50_1392 18 105.33
I need to combine all ordernumbers 10100 and their corresponding price values (30 * 171.70, etc.) to get the total value of the entire order. Is there some code that will combine all like-wise ordernumbers and output their total values?
Any help is greatly appreciated.
You need to compute order value and then using groupby
, sum the order value for each order.
df['order_value'] = df['quantityordered'] * df['priceeach']
df.groupby('ordernumber')['order_value'].sum().reset_index(name='total_order_value')
Output
ordernumber total_order_value
0 10100 12133.25
1 10101 3782.00
2 10425 10576.99
Let us do these things separately:
We can do that by:
df['pricequantity'] = df['priceeach'] * df['quantityordered']
then we can sum up the prices with:
df.groupby('ordernumber')['pricequantity'].sum()
For the given sample data (except the last line that was missing an orderlinenumber
), we get:
>>> df.groupby('ordernumber')['pricequantity'].sum()
ordernumber
10100 12133.25
10101 3782.00
10425 10576.99
Name: pricequantity, dtype: float64
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.