Issue
I want to create an expanded 1D array from elements of 1D array using some numpy operation and without using a for loop. I would essentially read in the elements of 1D array and count up a few numbers(pre-determined value) from it and proceed to the next element to expand. See an example below.
1D array = [1 9 20 56 78 120]
expanded 1D array = [1 2 3 9 10 11 20 21 22 56 57 58 78 79 80 120 121 122]
is this possible? Thank you
I honestly don't have any idea how to do this without using a for loop
Solution
a = np.array([1, 9, 20, 56 ,78, 120])
n = 3
out = (np.arange(n) + a[:,None]).ravel()
Edit: explanation
a[:, None]
is a shortcut for a.reshape(a.size, 1)
. It creates a 2 dimension array. When I want to sum with np.arange(n)
, this array is promoted to shape (1, n)
. Then numpy broadcasts all 1
to the matching dimension.
np.arange(n) + a[:,None]
has shape (a.size, n)
. Then ravel
is used to flatten it as a 1D array.
Answered By - Olivier Gauthé
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.