有效地组合两个numpy数组而不添加

时间:2022-04-06 22:55:18

I currently have two large numpy arrays of equivalent lengths. The first array is filled with values in sets of 5 that will either be a set of 5 float values or 5 0s as such:

我目前有两个等长的大型numpy数组。第一个数组填充5个集合中的值,这些值将是一组5个浮点值或5个0:

    [ [.03, 5, .1, 0.23, 5], [.1, .6, .8, 4.3], [0,0,0,0,0] ... ] 

The 2nd array is filled with values in the same fashion. I need to combine the two arrays so that at any position where array_two has a non zero value set, the corresponding position in array_one needs to be set to that value. If array_one already has a value then it should stay the same. That is kind of a mouthful so here is an example of what I am trying to explain should happen.

第二个数组以相同的方式填充值。我需要组合两个数组,以便在array_two设置非零值的任何位置,array_one中的相应位置需要设置为该值。如果array_one已经有一个值,那么它应该保持不变。这有点拗口,所以这里有一个我试图解释应该发生的例子。

    Array one:  [ [.03, 5, .1, 0.23, 5], [0,0,0,0,0], [.1, .6, .8, 4.3, .2], [0,0,0,0,0], [0,0,0,0,0] ... ]

    Array two: [ [0,0,0,0,0], [0,0,0,0,0], [.1, .6, .8, 4.3], [0,0,0,0,0], 
    [32 ,2 , 4.6 , 3.4 , 0.2] ... ]

The resulting array should be :

结果数组应该是:

    [ [.03, 5, .1, 0.23, 5], [0,0,0,0,0], [.1, .6, .8, 4.3, .2], [0,0,0,0,0], 
       [32 ,2 , 4.6 , 3.4 , 0.2] ...     ]

essentially the new array gets the value from array_two at position 5. This can't be accomplished with a sum because that would make position three twice what it should be.

本质上,新数组从位置5的array_two获取值。这不能通过求和来实现,因为这将使位置3成为应有的两倍。

1 个解决方案

#1


1  

numpy.where is ment for situations like this:

numpy.where适用于以下情况:

import numpy as np
wh = (a != 0).any(1, keepdim=True)
# or for numpy version < 1.7
wh = (a != 0).any(1)[:, np.newaxis]
c = np.where(wh, a, b)

In your case numpy.maximum might also work.

在你的情况下,numpy.maximum也可能有效。

c = np.maximum(a, b)

#1


1  

numpy.where is ment for situations like this:

numpy.where适用于以下情况:

import numpy as np
wh = (a != 0).any(1, keepdim=True)
# or for numpy version < 1.7
wh = (a != 0).any(1)[:, np.newaxis]
c = np.where(wh, a, b)

In your case numpy.maximum might also work.

在你的情况下,numpy.maximum也可能有效。

c = np.maximum(a, b)