簡體   English   中英

基於另一個數組替換 numpy 數組中的元素

[英]Replacing elements in numpy array based on another array

我有以下 numpy 數組:

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

我還有另一個數組:

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

我需要將第一個數組的每個“x”元素替換為第二個數組中相同“x”元素之后的元素。

這是預期的 output

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

我可以使用 np.where 循環來獲取第二個數組中每個“x”元素的索引,但我想有更好的方法來做到這一點。

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]]

現在following_numpy_array是:

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

請注意,如果要更新'CLU22' ,則會引發錯誤,因為在another_array中沒有元素之后

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM