我想转换一个这样的n维numpy数组:
[ [ a, b, c],
[ d, e, f] ]
到的2维阵列axis_0_index
,axis_1_index
,cell_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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句