簡體   English   中英

將n維numpy數組轉換為二維索引數組

[英]Convert n-dimensional numpy array to 2-dimensional index array

我想轉換一個n維numpy數組,如下這個:

[ [ a, b, c],
  [ d, e, f] ]

axis_0_indexaxis_1_indexcell_value的二維數組。

[ [ 0, 0, a],
  [ 0, 1, b],
  [ 0, 2, c],
  [ 1, 0, d],
  [ 1, 1, e],
  [ 1, 2, f] ]

這可以在NumPy中輕松完成嗎?

您可以使用(濫用?) np.where獲取數組的所有索引,使用與條件相同形狀的數組,然后使用(展平的)數組堆疊這些索引,最后轉置。

>>> A = np.array([ [ 'a', 'b', 'c'], [ 'd', 'e', 'f'] ])
>>> ones = np.ones(A.shape)
>>> np.vstack(np.where(ones) + (A.ravel(),)).transpose()
array([['0', '0', 'a'],
       ['0', '1', 'b'],
       ['0', '2', 'c'],
       ['1', '0', 'd'],
       ['1', '1', 'e'],
       ['1', '2', 'f']], 
      dtype='|S1')

經過一些搜索后,使用np.indices可能更干凈:

>>> X, Y = np.indices(A.shape)
>>> np.vstack((X.ravel(), Y.ravel(), A.ravel())).T

要么

>>> np.vstack((X, Y, A)).reshape(3,A.size).T

在兩種情況下,結果與上述相同。


我使用IPython的%timeit做了一些時序分析。 奇怪的是,我用第一溶液where似乎是最快的,至少在這個非常小的測試序列:

>>> %timeit f1() # using ones and np.where
10000 loops, best of 3: 72.3 us per loop
>>> %timeit f2() # using np.indices and ravel
10000 loops, best of 3: 125 us per loop
>>> %timeit f3() # using np.indices and reshape
10000 loops, best of 3: 110 us per loop
>>> %timeit g() # using meshgrid
10000 loops, best of 3: 134 us per loop

您可以使用np.meshgrid ,如下面的示例運行所示 -

In [19]: A
Out[19]: 
array([[19, 80, 63],
       [24, 54, 44]])

In [20]: m,n = A.shape

In [21]: R,C = np.meshgrid(np.arange(m),np.arange(n))

In [22]: np.column_stack((R.ravel('F'),C.ravel('F'),A.ravel()))
Out[22]: 
array([[ 0,  0, 19],
       [ 0,  1, 80],
       [ 0,  2, 63],
       [ 1,  0, 24],
       [ 1,  1, 54],
       [ 1,  2, 44]])

暫無
暫無

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

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