forwardfill combined with calculation (method='ffill' * xyz) in python pandas -
i need fill nan spaces calculation, depends on previous values in dataframe = df. have far this:
df = pd.dataframe({'a': [none] * 6, 'b': [2, 3, 10, 3, 5, 8]}) df["c"] =np.nan df["c"][0] = 1 df["c"][2] = 3 = 1 while i<10: df.c.fillna(df.c.shift(i)*df.b,inplace=true) i+1
unfortunately solution while loop not work , bad solution pandas. looking kind of a
df.c.fillna(method='ffill'*df.b,inplace=true)
i know doesn't work, think makes clearer looking for.
before filling dataframe looks this:
b c 0 2 1 1 3 nan 2 10 3 3 3 nan 4 5 nan 5 8 nan
the desired outcome should this:
b c 0 2 1 # nothing filled in since data set df["c"][0] = 1 1 3 3 # fill in previous c * b = 1 * 3 = 3 2 10 3 # nothing filled in since data set df["c"][2] = 3 3 3 9 # fill in previous c * b = 3 * 3 = 9 4 5 45 # fill in previous c * b = 9 * 5 = 45 5 8 360 # fill in previous c * b = 45 * 8 = 360
so basically: if there no data availabe, should filled caculation.
i can't figure out way in single loop, problem here want kind of rolling apply can @ previous row, problem here previous row update not observable until apply
finishes instance following works because in run apply 3 times. isn't great imo:
in [103]: def func(x): if pd.notnull(x['c']): return x['c'] else: return df.iloc[x.name - 1]['c'] * x['b'] df['c'] = df.apply(func, axis =1) df['c'] = df.apply(func, axis =1) df['c'] = df.apply(func, axis =1) df out[103]: b c 0 none 2 1 1 none 3 3 2 none 10 3 3 none 3 9 4 none 5 45 5 none 8 360
Comments
Post a Comment