user23299
user23299

Reputation: 17

How to delete an element in an array depending on another array modification in Python

I have two arrays:

x=np.array([0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,1])
y=np.array([y0,y1,y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12])

Where the elements y_i correspond only to the 0-elements in the array x.

I want to modify one random 0-element in x and to make it 1. At this time, I have to delete the corresponding element in y (because y contains only element related to 0 in the array x).

[EDIT:] for example, I have

x=np.array([0,0,0,0,0,1,1,0,0,1,0]
 y=np.array([21,32,45,54,87,90,88,60])

such that to x[0] corresponds y[0]=21, x[1]—> y[1]=32, x[2]—>y[2]=45, x[3]—> y[3]=54, x[4]—>y[4]=87, x[7]—>y[5]=90, x[8]—>y[6]=88, x[10]—>y[7]=60. If I change x[2], x[7] and x[10] from 0 to 1, I want to cancel the corresponding elements in y, i.e. 45, 90 and 60

Upvotes: 0

Views: 135

Answers (1)

atru
atru

Reputation: 4744

This may be what you are looking for:

x_0 = np.where(x==0)[0]

rand_ind = np.random.randint(1,len(x_0))

x[x_0[rand_ind]] = 1;

y = np.delete(y, rand_ind)

x_0 is an array of elements in x initially equal to 0. rand_ind is a random index chosen from x_0 length range. To change 0 to 1 the program uses x_0[rand_ind] while to delete the corresponding element in y it simply uses rand_ind.


This is a modified solution for the updated question,

import numpy as np
import random

x_0 = np.where(x==0)[0]

rand_ind = np.array(random.sample(list(x_0), 3))

x[rand_ind] = 1

y = np.delete(y, [np.where(x_0==i)[0] for i in rand_ind])

In this solution rand_ind is a direct choice of indices of the x array and not the trimmed x_0 array. It chooses the indices stored in x_0 to avoid choosing indexes where the value in x is 1. The indexes i.e. elements of x_0 are the indexes of x while the indexes of x_0 correspond to indexes/positions in y.

Program uses random.sample as a straightforward way to pick N elements at random without repetition (here 3). It then turns the elements at rand_ind in x to 1 and deletes the corresponding elements in y. The last step is done by using a generator and finding the indices of x_0 elements with each rand_ind value.

Upvotes: 1

Related Questions