I have a pandas data frame of which one column is date and another contains some value along with NaNs. Example, data frame is given below -
import pandas as pd
import numpy as np
df = pd.DataFrame({'a':pd.date_range(start="01/01/2013",periods=6, freq="D"),'b': [1,np.nan,np.nan,4,np.nan,7]})
df
a b
2013-01-01 1
2013-01-02 NaN
2013-01-03 NaN
2013-01-04 4
2013-01-05 NaN
2013-01-05 7
Now, i want to fill this NaNs with some fixed multiplier of previous value, i.e. above data frame will look something like this after transformation, if fixed multiplier is 0.5-
a b
2013-01-01 1
2013-01-02 0.5
2013-01-03 0.25
2013-01-04 4
2013-01-05 2
2013-01-05 7
One of the way of doing this would be to loop over b and then use .loc
function to transform it, i.e. we can use below given code snippet
for i in range(df.shape[0]):
if np.isnan(df.loc[i, 'b']):
df.loc[i, 'b'] = df.loc[i-1, 'b']*0.5
Though this works well, but it does not scale well - takes lot of time. So, it would be really helpful if someone can help me in doing it more efficiently using some pandas inbuilt function.
Thanks!