程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Pandas Skills] Grouping ratio calculation and summation

編輯:Python
Appreciation of beautiful pictures2022/08/01

Problem:In recent requirements development, there is such a groupProportion calculation and summation problem, group according to the field 'CPN', calculate the proportion of each PO Line Actual CT2R * line quantity, name it 'Weighted(QTY)CT2R', and then classify each line 'Weighted' according to the same 'CPN'(QTY)CT2R' value is summarized and summed to get the total 'Weighted(QTY)CT2R' value. The cell filled with yellow as shown in the figure below is the target value we need

The specific calculation logic is as follows:

Use Pandas code to achieve the above requirements as follows:

import pandas as pddf = pd.DataFrame([['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',10,90],['01-0989',200,50],['02-0437',20,80],['02-0437',20,80],['02-0437',20,80]],columns = ['cpn','po_line_qty','actual_ct2r'])# Group according to the field 'cpn', sum the values ​​in the field 'po_line_qty' and name it totaltotal = df.groupby('cpn').agg({'po_line_qty':sum}).reset_index()# Rename field 'po_line_qty' to 'total_po_line_qty'total = total.rename(columns = {'po_line_qty':'total_po_line_qty'})# The df table and the total table are left-joined according to the field 'cpn', named new_resnew_res = pd.merge(df,total,how='left',on='cpn')def weighted_qty_ct2r(row):scale = row['po_line_qty'] / row['total_po_line_qty']weighted_qty_ct2r = scale * row['actual_ct2r']return weighted_qty_ct2r# Generate field 'weighted_qty_ct2r'new_res['weighted_qty_ct2r'] = new_res.apply(lambda row:weighted_qty_ct2r(row), axis=1)# Group according to the field 'cpn', sum the values ​​in the field 'weighted_qty_ct2r' and name it df_resultdf_result = new_res.groupby('cpn').agg({'weighted_qty_ct2r':sum})

df

total

new_res

df_result


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved