Py-ser
Py-ser

Reputation: 2098

Mask array of different sizes, then replace elements from another one

I have two arrays of different size a and b, and I want to obtain a new array with the same size as the largest one (a_and_b), and with elements that have zeros everywhere except when the difference between any of the two elements is minimum. Then I want to replace its non-zero elements with the elements of another array of the same size as the first one

a = np.asarray([1, 3])
b = np.asarray([0.8, 0.95, 1.1, 1.25, 1.40, 1.55, 1.70, 1.85, 2.00, 2.15, 2.30, 2.45, 2.60, 2.75, 2.90, 3.05])
c = np.asarray([15.145, 18.191])

a_and_b = [0 0.95 0 0 0 0 0 0 0 0 0 0 0 0 0 3.05]
final = [0 15.145 0 0 0 0 0 0 0 0 0 0 0 0 0 18.191]

How do I obtain the final?

Upvotes: 0

Views: 387

Answers (1)

Mercury
Mercury

Reputation: 4146

Try this.

import numpy as np

a = np.asarray([1, 3])
b = np.asarray([0.8, 0.95, 1.1, 1.25, 1.40, 1.55, 1.70, 1.85, 2.00, 2.15, 2.30, 2.45, 2.60, 2.75, 2.90, 3.05])
c = np.asarray([15.145, 18.191])

a_and_b, final = np.zeros_like(b), np.zeros_like(b)
min_ba = (abs(b.reshape(1,-1)-a.reshape(-1,1)).argmin(axis=1))
a_and_b[min_ba] = b[min_ba]
final[min_ba] = c
print(a_and_b)
print(final)

Out:

[0.   0.95 0.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.   0.
 0.   3.05]
[ 0.    15.145  0.     0.     0.     0.     0.     0.     0.     0.
  0.     0.     0.     0.     0.    18.191]

Upvotes: 1

Related Questions