saifuddin778
saifuddin778

Reputation: 7298

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 (i.e. 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.

Upvotes: 15

Views: 6725

Answers (3)

user3483203
user3483203

Reputation: 51175

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

Upvotes: 7

pault
pault

Reputation: 43544

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.

Upvotes: 4

U13-Forward
U13-Forward

Reputation: 71610

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]

Upvotes: 2

Related Questions