Philipp K.
Philipp K.

Reputation: 163

Is there a faster or better way to combine two 2d-numpy arrays like OR without adding up numbers?

The Method describes my need.

def what_i_want(x, y):
    if not x:
        return y
    return x

x = np.array([[0, 0], [1, 1]])
y = np.array([[0, 2], [0, 2]])

My Solution works well, but larger arrays lead to long runtimes.

np.array([[what_i_want(k, l) for k, l in zip(i, j)] for i, j in zip(x, y)])

Output:

[[0 2]
 [1 1]]

Upvotes: 0

Views: 54

Answers (1)

Diego Palacios
Diego Palacios

Reputation: 1144

Using numpy functions will be much faster. This can be done with the np.where function, see the docs.

output = np.where(x, x, y)

Edit:

If you want to preserve the largest element in each position, use np.maximum

Upvotes: 3

Related Questions