简体   繁体   中英

Replacing elements in numpy array based on another array

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM