Reputation: 771
I have a question regarding multiple-conditions on pandas columns. I have the following dataframe:
A B C
0 0 9 0
1 1 8 0
2 1 9 0
3 1 5 1
4 1 9 1
5 1 8 1
6 -1 9 0
7 -1 5 -1
8 -1 7 -1
What I am trying to achieve is the following:
1.) If A>0 and B <6 C should become a 1 and keep that until A changes (B could get above 6)
2.) If A<0 and B <6 C should become a -1 and keep that until A changes (B could get above 6)
Any suggestions how to do that without a loop?
I am struggeling with how to "memorize" the status of B having been below 6 for the current A= 1 or A=-1 period.
Thanks for any suggestions
Upvotes: 1
Views: 223
Reputation: 323226
Using np.select
create your help column when satisfied your own conditions , then we do groupby
with bfill
s1=(df.A>0)&(df.B<6)
s2=(df.A<0)&(df.B<6)
df['v']=np.select([s1,s2],[1,-1])
df.v.replace(0,np.nan).groupby(df.A).ffill().fillna(0).astype(int)
Out[1023]:
0 0
1 0
2 0
3 1
4 1
5 1
6 0
7 -1
8 -1
Upvotes: 1