Pandas: np.where with multiple conditions for data frames

Hi folks, I look all over SO and google and can't find anything like it ...

I have a dataframe x (essentially consisting of one row and 300 columns) and another dataframe y with the same size but with different data. I would like to change x so that it is 0 if it has a different sign for y And x itself is not equal to 0, otherwise leave it as it is. so this requires using np.where with several conditions. However, in the examples of several conditions, I saw that everyone uses scalars, and when I use the same syntax, it does not seem to work (the installation ends β€” everything is to zero, without errors). I'm worried about link assignment issues hidden somewhere else (y - x after the offset, but how much can I judge that this code does not exist above) any ideas?

The code I'm trying to debug is:

tradesmade[i:i+1] = np.where((sign(x) != sign(y)) & (sign(x) != 0), 0, x) 

which returns a bunch of zeros. I also tried

 tradesmade[i:i+1][(sign(x) != sign(y)) * (sign(x) != 0)] = 0 

but it doesn’t work either. I was in this for hours and to complete loss. please, help!

+5
source share
2 answers

It’s not clear to me what exactly you want to do when the y element is zero ... in any case, the key point in this answer is "using np.logical_{and,not,or,xor} functions".

I think that the following, although formulated differently than your example, does what you want, but if I am mistaken, you should be able to combine different tests to achieve what you want,

 x = np.where(np.logical_or(x*y>0, y==0), x, 0) 
+11
source

Similar to the @gboffi post, but more centralized for your initial request as per my understanding, try:

 x = np.where(np.logical_and((x*y) < 0, x != 0)) 

or

 x = np.where(((x*y) < 0) & (x != 0))) 
+4
source

Source: https://habr.com/ru/post/1210162/


All Articles