-1

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.

younggotti
  • 762
  • 2
  • 15
  • Does this answer your question? [Fast replacement of values in a numpy array](https://stackoverflow.com/questions/3403973/fast-replacement-of-values-in-a-numpy-array) – MangoNrFive Jul 29 '22 at 08:53
  • The keys and values of the mapping can be extracted by `keys=other_array[:-1]` and `values=other_array[1:]` – MangoNrFive Jul 29 '22 at 08:56

1 Answers1

1
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