python - Duplicate array dimension with numpy (without np.repeat) -


i'd duplicate numpy array dimension, in way sum of original , duplicated dimension array still same. instance consider n x m shape array (a) i'd convert n x n x m (b) array, a[i,j] == b[i,i,j]. unfortunately np.repeat , np.resize not suitable job. there numpy function use or possible creative indexing?

>>> import numpy np >>> = np.asarray([1, 2, 3]) >>> array([1, 2, 3]) >>> a.shape (3,) # not want... >>> np.resize(a, (3, 3)) array([[1, 2, 3],        [1, 2, 3],        [1, 2, 3]]) 

in above example, result:

array([[1, 0, 0],        [0, 2, 0],        [0, 0, 3]]) 

from 1d 2d array, can use np.diagflat method, create two-dimensional array flattened input diagonal:

import numpy np = np.asarray([1, 2, 3])  np.diagflat(a) #array([[1, 0, 0], #       [0, 2, 0], #       [0, 0, 3]]) 

more generally, can create zeros array , assign values in place advanced indexing:

a = np.asarray([[1, 2, 3], [4, 5, 6]])  result = np.zeros((a.shape[0],) + a.shape) idx = np.arange(a.shape[0]) result[idx, idx, :] =  result #array([[[ 1.,  2.,  3.], #        [ 0.,  0.,  0.]],  #       [[ 0.,  0.,  0.], #        [ 4.,  5.,  6.]]]) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -