Sebastian
Sebastian

Reputation: 795

numpy: How do I pick rows from two 2D arrays based on conditions in 1D arrays?

I have two arrays of length n, namely old_fitness and new_fitness, and two matrices of dimension nxm, namely old_values and new_values.

What is the best way to create an nxm matrix best_fitness that comprises row new_values[i] when new_fitness[i] > old_fitness[i] and old_values[i] otherwise?

Something like:

best_values = nd.where(new_fitness > old_fitness, new_values, old_values)

but that works on rows of the last two matrices, instead of individual elements? I'm sure there's an easy answer, but I am a complete newbie to numpy.

Edit: new_values and old_values contain rows that represent possible solutions to a problem, and new_fitness and old_fitness contain a numeric measure of fitness for each possible solution / row in new_values and old_values respectively.

Upvotes: 1

Views: 56

Answers (3)

Patol75
Patol75

Reputation: 4547

Another possible solution, working on numpy arrays:

best_values = numpy.copy(old_values)
best_values[new_fitness > old_fitness, :] = new_values[new_fitness > old_fitness, :]

Upvotes: 1

Sebastian Scholl
Sebastian Scholl

Reputation: 1095

Are the arrays of equal length? If so zip them and then use a map function to return the desired output.

For example, something like:

bests = map(new_val if new_val > old_val else old_val for (old_val, new_val) in zip(old_fitness, new_fitness))

Edit: this is probably better

bests = map(lambda n, o: n if n > o else o, new_fitness, old_fitness)

Here's another one that works too!

bests = [np.max(pair) for pair in zip(new_fitness, old_fitness)]

Upvotes: 0

N.Clarke
N.Clarke

Reputation: 268

Should work as long as the comparison is of shape (n,1) - not (n,)

import numpy as np

old_fitness = np.asarray([0,1])
new_fitness = np.asarray([1,0])

old_value = np.asarray([[1,2], [3,4]])
new_value = np.asarray([[5,6], [7,8]])

np.where((new_fitness>old_fitness).reshape(old_fitness.shape[0],1), new_value, old_value)

returns

array([[5, 6],
       [3, 4]])

Upvotes: 2

Related Questions