1

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

1
  • Index B A A>0 & B >0.8 A>0 & as soon as B>0.8 2127 0.551354566 0 0 0 2128 0.66838571 0 0 0 2129 0.809306329 1 1 1 2130 0.812775762 1 1 1 2131 0.81319083 1 1 1 2132 0.814134565 1 1 1 2133 0.814281433 1 1 1 2134 0.812157799 1 1 1 2135 0.810377385 1 1 1 2136 0.808989447 1 1 1 2137 0.806981847 1 1 1 2138 0.800548453 1 1 1 2139 0.792510453 1 0 0 2140 0.785009569 1 0 0 2141 0.777099821 1 0 0 2142 0.768469301 1 0 0 2143 0.762370584 1 0 0 2144 0.754136153 1 0 0 2145 0.74586568 1 0 0 2146 0.74058505 1 0 0 2147 0.733714521 1 0 0 Commented Oct 8, 2018 at 16:58

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

6 Comments

did OP want output to be float rather than int?
@pygo adding astype(int)
Many thanks Wen!! Sorry, trying to understand the code. Why would you goupby A and use ffill?
Unfortunately it seems also not to solve the issue. Here is the concrete example. Index is time.
Tried to add it but somehow the format is not readable when I copy the table here
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.