I have this data:
# df
ID Col1
A -4
A -3
A -2
A -1
A 1
A 2
A 9992
B -4
B -3
B -2
B -1
B 9
B 13
B 21
B 38
B 9992
I want to create a new column Col_NEW with forward fill or rolling calculation based on Col1 by ID.
The final result:
# df
ID Col1 Col_NEW
A -4 -4
A -3 -3
A -2 -2
A -1 -1
A 1 0
A 2 2
A 9992 3
B -4 -4
B -3 -3
B -2 -2
B -1 -1
B 9 0
B 13 10
B 21 14
B 38 22
B 9992 39
The logic is as below:
- If
Colis-4,-3,-2,-1, thenCol_NEWare the same. - Otherwise,
Col_NEWwill be theCol1forward filling and plus 1.
I tried this but is there any way to create Col_NEW directly?
df["Col_NEW"] = df.groupby('ID')['Col1'].transform(lambda x: (x.shift(1) + 1))
Any idea?