SoFunction
Updated on 2024-11-17

A detailed explanation of the vectorial trinomial operator in numpy

If you are using data filtering, you can use the x if condition else y logic to implement it. If you are using pure Python, you can use constant iteration to filter each combination of elements accordingly. However, if you use numpy in the vectorization counter can greatly accelerate the process.

In numpy there is a vector version of this trinomial operation. where method can take three arguments, the first argument is a conditional vector, while the second and third arguments can be matrices or scalars. The next step is to do a pure Python implementation of the corresponding function as well as a vector implementation.

The record is as follows:

In [76]: xarr = ([1.1,1.2,1.3,1.4,1.5])

In [77]: yarr = xarr + 1


In [78]: xarr
Out[78]: array([ 1.1, 1.2, 1.3, 1.4, 1.5])


In [79]: yarr
Out[79]: array([ 2.1, 2.2, 2.3, 2.4, 2.5])


In [80]: cond = ([True,False,True,True,False])


In [81]: cond
Out[81]: array([ True, False, True, True, False], dtype=bool)


In [82]: result1 = [(x if c else y) for x,y,c in zip(xarr,yarr,cond)]


In [83]: result1
Out[83]: [1.1000000000000001, 2.2000000000000002, 1.3, 1.3999999999999999, 2.5]


In [84]: result2 = (cond,xarr,yarr)


In [85]: result2
Out[85]: array([ 1.1, 2.2, 1.3, 1.4, 2.5])

In terms of the floating point representation, there is a tiny little difference between the two, in multiple decimal places, which can usually be ignored in numerical representations. Still, it's important to make a little consistency judgment of the two results here, as I've seen Python's differences in floating-point representations due to the machine before.

The results of the test are as follows:

In [87]: result1 == result2
Out[87]: array([ True, True, True, True, True], dtype=bool)

As you can see from the results above, the two calculations are consistent.

Above this on numpy in the vectorial trinomial operator details is all I share with you, I hope to give you a reference, and I hope you support me more.