在numpy数组中组合值

时间:2016-03-24 14:01:36

标签: python arrays numpy

我有一些具有相同大小MxN的numpy数组(SVM预测)。我需要创建一个具有相同大小但只有每个位置的较高值的新的。例如:

[[1,2,1,3],         [[2,1,5,1],          [[2,2,5,3],
 [2,5,2,1]]   and   [1,3,5,5]]   result   [2,5,5,5]]
 [4,1,3,1]]         [4,2,1,2]]            [4,2,3,2]]

总和和产品是这样的:predict = a * b * c,其中a, b and c是与其他预测读取的相同大小的numpy数组。

谢谢。

3 个答案:

答案 0 :(得分:7)

您可以使用numpy.maximum计算输入数组之间的元素最大值。

A = np.array([[1,2,1,3], [2,5,2,1], [4,1,3,1]])
B = np.array([[2,1,5,1], [1,3,5,5], [4,2,1,2]])

C = np.maximum(A, B)

# array([[2, 2, 5, 3],
#        [2, 5, 5, 5],
#        [4, 2, 3, 2]])

答案 1 :(得分:3)

您可以使用np.where -

np.where(a>b,a,b)

此处np.where根据a的掩码在ba>b之间进行选择,从而模拟a中相应元素的最大值选择b

答案 2 :(得分:1)

您可以在第0轴使用np.max()

>>> np.max((a,b), axis=0)
array([[2, 2, 5, 3],
       [2, 5, 5, 5],
       [4, 2, 3, 2]])