Pandas Function To Create Combined Column Based On Dict
I am trying to create a weighted column in a pandas.DataFrame I have a python dictionary with the keys being the pandas.DataFrame column names and the values the corresponding weig
Solution 1:
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
Post a Comment for "Pandas Function To Create Combined Column Based On Dict"