Skip to content Skip to sidebar Skip to footer

Forwardfill Combined With Calculation (method='ffill' * Xyz) In Python Pandas

I need to fill NaN spaces with a calculation, that depends on the previous values in the dataframe = df. What I have so far is this: df = pd.DataFrame({'a': [None] * 6, 'b': [2, 3,

Solution 1:

I can't figure out a way to do this in a single loop, the problem here is that you want some kind of rolling apply that can then look at the previous row, the problem here is that the previous row update will not be observable until the apply finishes so for instance the following works because we in run the apply 3 times. This 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]:
      a   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

Post a Comment for "Forwardfill Combined With Calculation (method='ffill' * Xyz) In Python Pandas"