Reputation: 725
I want to count the number of elements in a row and subtract a value based on the previous element. I can do it in a for loop, but it is too slow. I want to charge a $7 fee every time either 0 or 2 appears in the Target column, but not if the previous Target is equal to the current target. $0 fee for Target == 1, and $7 fee if new target appears that is not 1 or the current target. I have Target in my df, but i want to calculate Fee. Example on df
input:
df.head(10)
Target Fee
1 0
1 0
1 0
0 -7
0 0
0 0
2 -7
2 0
1 0
2 -7
Upvotes: 0
Views: 52
Reputation: 150735
IIUC:
df['Fee'] = (df.Target.diff().ne(0) & df.Target.isin([0,2])) * (-7)
Output:
Target Fee
0 1 0
1 1 0
2 1 0
3 0 -7
4 0 0
5 0 0
6 2 -7
7 2 0
8 1 0
9 2 -7
Upvotes: 1