简体   繁体   English

numpy:如何根据一维数组中的条件从两个2D数组中选择行?

[英]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 . 我有两个长度为n数组,即old_fitnessnew_fitness ,以及两个维数为nxm矩阵,即old_valuesnew_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? new_fitness[i] > old_fitness[i]old_values[i]否则,创建包含行new_values[i]nxm矩阵best_fitness的最佳方法是什么?

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. 我确信这是一个简单的答案,但我是一个完全新手的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. 编辑: new_valuesold_values包含表示问题的可能解决方案的行, new_fitnessold_fitness包含new_valuesold_values每个可能解决方案/行的适用度的数字度量。

Should work as long as the comparison is of shape (n,1) - not (n,) 只要比较是形状(n,1)就应该工作 - 不是(n,)

import numpy as np 导入numpy为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]])

Another possible solution, working on numpy arrays: 另一个可能的解决方案,处理numpy数组:

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

Are the arrays of equal length? 数组的长度是否相等? If so zip them and then use a map function to return the desired output. 如果是这样拉链它们然后使用map函数返回所需的输出。

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)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM