Inspired by the post How to create a sequence of sequences of numbers in R?.
Question:
I would like to make the following sequence in NumPy.
[1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5]
I have tried the following:
- Non-generic and hard coding using
np.r_
np.r_[1:6, 2:6, 3:6, 4:6, 5:6] # array([1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5])
- Pure Python to generate the desired array.
n = 5 a = np.r_[1:n+1] [i for idx in range(a.shape[0]) for i in a[idx:]] # [1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5]
- Create a 2D array and take the upper triangle from it.
n = 5 a = np.r_[1:n+1] arr = np.tile(a, (n, 1)) print(arr) # [[1 2 3 4 5] # [1 2 3 4 5] # [1 2 3 4 5] # [1 2 3 4 5] # [1 2 3 4 5]] o = np.triu(arr).flatten() # array([1, 2, 3, 4, 5, # 0, 2, 3, 4, 5, # 0, 0, 3, 4, 5, # This is 1D array # 0, 0, 0, 4, 5, # 0, 0, 0, 0, 5]) out = o[o > 0] # array([1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5])
The above solution is generic but I want to know if there's a more efficient way to do it in NumPy.