来自不同数据框的总和值

时间:2018-07-18 21:24:17

标签: python group-by conditional-statements

我有以下数据框:

print(X)

Quantity   Class    
   1         0
   5         0
   6         1
   8         2
   9         3
   0         4
...

print(dframe)

   Pred_class    Delta
           0  -0.046348
           1   1.856508
           2  20.347518
           3  -7.138728
           4   6.642686

我想为X创建一个附加列-“ Final_Q”-X [“ Quantity”]和对应的“ Delta”之和,每个类

打印(X)

Quantity   Class    Final_Q  
   1         0        1 - (-0.046348) 
   5         0        5 - (-0.046348)
   6         1        6 - (+1.856508)
...

我尝试过:

for i in np.unique(X["Class"]):

        #Isolate     
        X["Class"] == i
        dframe["Pred_class"] == i

        X_test_virtuale["BOOST"] = X_test_virtuale["ALG_N_forecast"] - dframe.iloc[0,0]

但是它似乎无法正常工作;

2 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么首先要合并:

 X = X.merge(dframe, how='left', left_on='Class', right_on='Pred_class')

,然后您只需按常规添加:

 X['Final_Q'] = X['Quantity'] + X['Delta']

这将为您带来帮助:

   Class  Quantity      Delta  Pred_class    Final_Q
0      0         1  -0.046348           0   0.953652
1      0         5  -0.046348           0   4.953652
2      1         6   1.856508           1   7.856508
3      2         8  20.347518           2  28.347518
4      3         9  -7.138728           3   1.861272
5      4         0   6.642686           4   6.642686

答案 1 :(得分:0)

按如下所示重命名func imageFromView(_ view: UIView) -> UIImage { UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0) view.drawHierarchy(in: view.frame, afterScreenUpdates: true) let snapshotImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return snapshotImage } 后即可使用pandas merge_asof。

Pred_class

dframe = dframe.rename(columns={'Pred_class':'Class'}) s = pd.merge_asof(X, dframe, on='Class') s['FinalQ'] = s['Quantity'] - s['Class']