Suppose I have 2 one-dimensional numpy arrays k
and d
. I want to perform a simple calculation between each element of array k
and whole array d
.
How may I do it without a for loop? I would like to do a vector calculation.
>>> k = np.array([4.1, 3.2, 1.2, 99.2])
>>> d= np.array([ 0., 2., 4., 8., 14., 100.])
>>>
>>> for kk in k:
... print 6 - (kk >= d).sum()
...
3
4
5
1
>>> 6 - (k >= d).sum()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (6,)
Have also tried the following and didn't work
>>> d = np.array([[ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.]])
>>> k = np.array([4.1, 3.2, 1.2, 99.2])
>>> 6 - (k >= d).sum()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (4,6)
>>>
CodePudding user response:
The key here is to index one of the arrays with [:, None]
. That will prefix their shape
with 1
, causing each item of the array to be encased in its own array. That way, numpy will create a grid of calculations:
>>> 6 - (k[:, None] >= d).sum(axis=1)
array([3, 4, 5, 1])