简体   繁体   中英

Populate values from one numpy array into another

I have some data in a numpy array, for example:

a = np.array([1,2,3,4,5,6,7,8,9,10])

I then want to subset some values from this array, ie:

b = a[a > 5]

so that:

b = np.array([6,7,8,9,10])

I then conduct some simple calculations on this subset, ie:

c = b + 1

so that:

c = np.array([7,8,9,10,11])

I then want to repopulate the original array with the updated values, so that I end up with:

d = np.array([1,2,3,4,5,7,8,9,10,11])

My real data is obviously more involved than this so I would like to avoid doing it in one line just by indexing the values of interest from the original array (unless of course this is the easiest way of doing it).

Any help provided to populate the values in array c back into array a in order to get to array d would be much appreciated.

You could write:

>>> a[a > 5] += 1
>>> a
array([ 1,  2,  3,  4,  5,  7,  8,  9, 10, 11])

The += modifies the array in place.


To save an array of the indices of where a > 5 holds true, you can use np.where (or equivalently np.nonzero as per EdChum's suggestion):

>>> np.where(a > 5)
(array([5, 6, 7, 8, 9]),)

(This returns a tuple of index arrays - one for each dimension of a .)

You can use np.where :

In [55]:

np.where(a > 5, a + 1, a)
Out[55]:
array([ 1,  2,  3,  4,  5,  7,  8,  9, 10, 11])

The first param is the boolean condition, the second is the return value if the condition is true, the third param is the return value if false.

If you want to generate a new array what you could is instead of taking a copy of the array that you want to modify is to instead store the boolean mask:

In [56]:

a = np.array([1,2,3,4,5,6,7,8,9,10])
b = a > 5
b
Out[56]:
array([False, False, False, False, False,  True,  True,  True,  True,  True], dtype=bool)

In [57]:

d = np.where(b, a + 1, a)
d
Out[57]:
array([ 1,  2,  3,  4,  5,  7,  8,  9, 10, 11])

The original array is untouched

In [58]:

a
Out[58]:
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

If you want the index values you can use np.nonzero :

In [84]:

np.nonzero(b)
Out[84]:
(array([5, 6, 7, 8, 9], dtype=int64),)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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