1

I'd like to duplicate a numpy array dimension, but in a way that the sum of the original and the duplicated dimension array are still the same. For instance consider a n x m shape array (a) which I'd like to convert to a n x n x m (b) array, so that a[i,j] == b[i,i,j]. Unfortunately np.repeat and np.resize are not suitable for this job. Is there another numpy function I could use or is this possible with some creative indexing?

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

In the above example, I would like to get this result:

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

1 Answer 1

2

From 1d to 2d array, you can use the np.diagflat method, which Create a two-dimensional array with the flattened input as a diagonal:

import numpy as np
a = np.asarray([1, 2, 3])

np.diagflat(a)
#array([[1, 0, 0],
#       [0, 2, 0],
#       [0, 0, 3]])

More generally, you can create a zeros array and assign values in place with 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, :] = a

result
#array([[[ 1.,  2.,  3.],
#        [ 0.,  0.,  0.]],

#       [[ 0.,  0.,  0.],
#        [ 4.,  5.,  6.]]])
Sign up to request clarification or add additional context in comments.

2 Comments

np.diagflat(a) doesn't work correctly. a.shape = (2, 3) turns into np.diagflat(a).shape = (6, 6), but I need a shape of (2, 2, 3).
np.diagflat only works if you have 1d array and want to convert it to 2d array with 1d as diagonal, for a 2d array, you'll have to use the second more general solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.