Reputation: 125
I have a dataframe.
Here is the code for the column 'final_score':
weights = [0.3,0.1,0.1,0.5]
df.mul(weights).sum(axis=1)
As you can see, I am trying to set weights and multiply each value to get a score (listed in final_score). However there are some values that are None (NaN). My question is how do I change the weights so that the weights weigh more in other columns when an instance(s) of None is shown.
For example, in row2 all the values are present therefore the weights that I have assigned are calculating as accordingly. In rows 0 and 1, how can I shift the weights such that there is no weight City_score and the weight is instead shifted to the other three columns (ex. [0.3,0,0.1,0.6])
Upvotes: 1
Views: 786
Reputation: 15488
You can just use df.fillna()
:
df.fillna(0).mul(weights).sum(axis=1)
Upvotes: 1
Reputation: 2502
You could just replace all NaN
values with 0
and so when the weight is applied to that cell it will automatically become 0 (i.e. the weight will proportionally shift to the other columns).
There is a method in Pandas to do this: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html
Upvotes: 1