Suppose I have a DataFrame (or Series) like this:
Value
0 0.5
1 0.8
2 -0.2
3 None
4 None
5 None
I wish to create a new Result column.
The value of each result is determined by the previous Value, via an arbitrary function f.
If the previous Value is not available (None or NaN), I wish to use instead the previous Result (and apply f to it, of course).
Using the previous Value is easy, I just need to use shift. However, accessing the previous result doesn't seem to be that simple.
For example, the following code calculates the result, but cannot access the previous result if needed.
df['Result'] = df['Value'].shift(1).apply(f)
Please assume that f is arbitrary, and thus solutions using things like cumsum are not possible.
Obviously, this can be done by iteration, but I want to know if a more Panda-y solution exists.
df['Result'] = None
for i in range(1, len(df)):
value = df.iloc[i-1, 'Value']
if math.isnan(value) or value is None:
value = df.iloc[i-1, 'Result']
df.iloc[i, 'Result'] = f(value)
Example output, given f = lambda x: x+1:
Bad:
Value Result
0 0.5 NaN
1 0.8 1.5
2 -0.2 1.8
3 NaN 0.8
4 NaN NaN
5 NaN NaN
Good:
Value Result
0 0.5 NaN
1 0.8 1.5
2 -0.2 1.8
3 NaN 0.8
4 NaN 1.8 <-- previous Value not available, used f(previous result)
5 NaN 2.8 <-- same