简体   繁体   中英

Replace multiple elements in numpy array with 1

In a given numpy array X :

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

I would like to replace indices (2, 3) and (7, 8) with a single element -1 respectively, like:

X = array([1,2,-1,5,6,7,-1,10])

In other words, I replaced values at indices (2, 3) and (7,8) of the original array with a singular value.

Question is: Is there a numpy-ish way (ie without for loops and usage of python lists) around it? Thanks.

Note: This is NOT equivalent of replacing a single element in-place with another. Its about replacing multiple values with a "singular" value. Thanks.

A solution using numpy.delete , similar to @pault, but more efficient as it uses pure numpy indexing. However, because of this efficient indexing, it means that you cannot pass jagged arrays as indices

Setup

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

a[idx] = -1
np.delete(a, idx[:, 1:])

array([ 1,  2, -1,  5,  6,  7, -1, 10])

I'm not sure if this can be done in one step, but here's a way using np.delete :

import numpy as np
from operator import itemgetter

X = np.array(range(1,11))
to_replace = [[2,3], [7,8]]


X[list(map(itemgetter(0), to_replace))] = -1
X = np.delete(X, list(map(lambda x: x[1:], to_replace)))
print(X)
#[ 1  2 -1  5  6  7 -1 10]

First we replace the first element of each pair with -1 . Then we delete the remaining elements.

Try np.put :

np.put(X, [2,3,7,8], [-1,0]) # `0` can be changed to anything that's not in the array
print(X[X!=0]) # whatever You put as an number in `put`

So basically use put to do the values for the indexes, then drop the zero-values.

Or as @khan says, can do something that's out of range:

np.put(X, [2,3,7,8], [-1,np.max(X)+1])
print(X[X!=X.max()])

All Output:

[ 1  2 -1  5  6  7 -1 10]

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