且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

pandas 函数基于dict创建组合列

更新时间:2022-12-09 11:50:06

首先创建 Index.intersection ,然后选择此列,并与 dot Series from dict仅针对同一列进行过滤:

First create variable for same values for columns and keys in dictionary by Index.intersection, then select this columns and use matrix multiplication with dot with Series from dict filtered for same columns only:

df['Composite'] = df['IX1']*0.3 + df['IX2']*0.2 + df['IX3']*0.4

cols = df.columns.intersection(weights.keys())
df['Composite1'] = df[cols].dot(pd.Series(weights)[cols])
print (df)
        IX1       IX2       IX3  Composite  Composite1
0  1.764052  0.400157  0.978738   1.000742    1.000742
1  2.240893  1.867558 -0.977278   0.654868    0.654868
2  0.950088 -0.151357 -0.103219   0.213468    0.213468
3  0.410599  0.144044  1.454274   0.733698    0.733698
4  0.761038  0.121675  0.443863   0.430192    0.430192
5  0.333674  1.494079 -0.205158   0.316855    0.316855
6  0.313068 -0.854096 -2.552990  -1.098095   -1.098095
7  0.653619  0.864436 -0.742165   0.072107    0.072107
8  2.269755 -1.454366  0.045759   0.408357    0.408357
9 -0.187184  1.532779  1.469359   0.838144    0.838144