Home > other >  Replacing elements in numpy array based on another array
Replacing elements in numpy array based on another array

Time:07-30

I have the following numpy array:

[['CLU20']
 ['CLZ20']
 ['CLH21']]

I also have another array:

['CLU20' 'CLZ20' 'CLH21' 'CLM21' 'CLU21' 'CLZ21' 'CLH22' 'CLM22' 'CLU22']

I need to replace each "x" element of the first array with the element following the same "x" element in the second array.

This is the expected output

[['CLZ20']
 ['CLH21']
 ['CLM21']]

I could do this with a loop using np.where to get the index of every "x" element in the second array, but I guess there's a better way to do this.

CodePudding user response:

following_numpy_array = np.array([
    ['CLU20'], ['CLZ20'], ['CLH21']
]) #why not to flat this array? do you need both shapes?

another_array = np.array(['CLU20','CLZ20','CLH21','CLM21','CLU21','CLZ21','CLH22','CLM22','CLU22'])

#find the indices in `another_array` and add 1 (cose we need the follow position)
ids = np.argwhere(following_numpy_array.repeat(len(another_array), axis=1)==another_array)
ids[:,1] =1

#update
following_numpy_array[ids[:,0], 0] = another_array[ids[:,1]]

Now following_numpy_array is:

array([['CLZ20'],
       ['CLH21'],
       ['CLM21']], dtype='<U5')

Note that if you want to update 'CLU22' it will raise an error because there are no elements after it in another_array

  • Related