Is there a universal function in numpy?

I have three episodes. I need to follow these steps:

  • Compare values ​​from the first and second series.
  • If first more, take the arc sine of the element from the third series.
  • Otherwise, take the arc cosine.

This is what I have managed to do so far:

numpy.if(numpy.less(s1,s2),numpy.arcsin(s3),numpy.arccos(s3)) 

Unfortunately, if it does not work, because numpy.if does not exist. Is there any way to overcome this problem?

+4
source share
2 answers

I think you are looking for numpy.where :

 np.where(s1<s2, np.arcsin(s3), np.arccos(s3)) 

For 1D inputs

 where(condition, [x, y]) 

equivalently

 [xv if c else yv for (c,xv,yv) in zip(condition,x,y)] 
+5
source

unutbu did great. I suggest one equivalent without where (but with numpy anyway)

 import numpy as np s1=[2,1,2,5,4,6] s2=[1,2,4,5,7,8] s3=[0.1,0.4,0.5,0.6,0.1,0.1] res = [xv if c else yv for (c,xv,yv) in zip([si1<si2 for si1,si2 in zip(s1,s2)], list(np.arcsin(s3)), list(np.arccos(s3)))] 

If you print zip() you get this list

 >>> [(False, 0.1001674211615598, 1.4706289056333368), (True, 0.41151684606748806, 1.1592794807274085), (True, 0.52359877559829893, 1.0471975511965979), (False, 0.64350110879328437, 0.9272952180016123), (True, 0.1001674211615598, 1.4706289056333368), (True, 0.1001674211615598, 1.4706289056333368)] 

Take the first element (False, 0.1001674211615598, 1.4706289056333368) : 2<1 really false. So you will have 1.4706289056333368 as the first value in res .

Result

 >>> res [1.4706289056333368, 0.41151684606748806, 0.52359877559829893, 0.9272952180016123, 0.1001674211615598, 0.1001674211615598] 
0
source

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


All Articles