Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
khan Avatar asked Oct 26 '18 02:10

khan


2 Answers

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])
like image 197
user3483203 Avatar answered Sep 16 '22 15:09

user3483203


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.

like image 45
pault Avatar answered Sep 17 '22 15:09

pault