簡體   English   中英

對NumPy數組進行排序

[英]Sorting a NumPy array

我有一個np數組,以下列方式構建為2個其他數組的交集:

第一個數組是:

[['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ...,
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

第二個數組是:

[['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ...,
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

實際上兩個數組之間存在多個差異,但它們主要出現在中間行中。

用於構造交集的代碼是:

def multidim_intersect(arr1, arr2):
    arr1_view = arr1.view([('',arr1.dtype)]*arr1.shape[1])
    arr2_view = arr2.view([('',arr2.dtype)]*arr2.shape[1])
    intersected = np.intersect1d(arr1_view, arr2_view)
    return intersected.view(arr1.dtype).reshape(-1, arr1.shape[1])

輸出的數組是:

[['!' '!']
 ['!' '! !']
 ['!' '! ! !']
 ...,
 ['}' 'was']
 ['}' 'was postponed']
 ['}' '{of']]

正如您所看到的,我的新數組的排序與原始的兩個數組(在單個感嘆號之前排序有多個驚嘆號,在LC_ALL = C排序中完成)的排序不同。 有沒有辦法像我的其他數組那樣對輸出的數組進行排序? 請注意,陣列的形狀很重要。

@Mr E arr1和arr2最初是列表。 我不能給你完整的副本,但我會盡我所能構建一個例子來說明我需要的東西。

arr1 = [['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ['!' '!']
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

arr2 = [['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ['!' '!']
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

理想情況下,輸出將是:

[['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ['!' '!']
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

但它是:

[['!' '!']
 ['! ! !' '! ! ! !']
 ['! ! !' '! ! ! "']
 ['! ! !' '! ! ! .']
 ['}' 'was postponed']
 ['}' 'was']
 ['}' '{of']]

或者那種效果。

我不太了解您的輸入格式,但您可以根據自己的需要進行調整。

問題是numpy.intersect1d()由於某種原因自動對輸出進行排序。 幸運的是,使用numpy.in1d()編寫自己的交集函數並不困難。 你可以這樣做:

import numpy as np

arr1 = np.array([['! ! !' '! ! ! !'],
 ['! ! !' '! ! ! "'],
 ['! ! !' '! ! ! .'],
 ['!' '!'],
 ['a' 'ad'],   # Stuff you don't want to get back
 ['}' 'was postponed'],
 ['}' 'was'],
 ['}' '{of']])

arr2 = np.array([['! ! !' '! ! ! !'],
 ['! ! !' '! ! ! "'],
 ['! ! !' '! ! ! .'],
 ['!' '!'],
 ['b' 'ab'],   # Stuff you don't want to get back
 ['}' 'was postponed'],
 ['}' 'was'],
 ['}' '{of']])

inarr = np.in1d(arr1, arr2)

arr3 = np.empty( shape=(0, 0) )

for i in np.arange(len(arr1)):
  if (inarr[i]):
    arr3 = np.append(arr3,arr1[i])

for i in np.arange(len(arr3)):
  print(arr3[i])

輸出:

! ! !! ! ! !
! ! !! ! ! "
! ! !! ! ! .
!!
}was postponed
}was
}{of

暫無
暫無

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

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