I have an array like -
x = array([0, 1, 2, 3,4,5])
And I want the output like this -
[]
[1]
[1 2]
[1 2 3]
[1 2 3 4]
[1 2 3 4 5]
I tried this code-
y = np.array([np.arange(1,i) for i in x+1])
But it makes a list with dtype object which I dont want. I want it ot be integer so that I can indexed it later.
-
3You cannot have an ordinary numpy array with non-uniform shape. That is, each row must be the same size if you want a 2d numpy array with the handy numpy indexing and slicing. This is why you get a 1d array of 1d arrays, it's just like a list of lists, except each item is an array.askewchan– askewchan2013年05月14日 17:43:45 +00:00Commented May 14, 2013 at 17:43
2 Answers 2
If I understand the question correctly, is
y = [np.arange(1,i) for i in x+1]
suitable? You can access the lists that make up the rows with y[r], e.g.,
>>> y[2]
array([1, 2])
or the whole lot with y:
>>> y
[array([], dtype=int64),
array([1]),
array([1, 2]),
array([1, 2, 3]),
array([1, 2, 3, 4]),
array([1, 2, 3, 4, 5])]
Also note that you can control the data type of the arrays returned by arange here by setting dtype=int (or similar).
answered May 14, 2013 at 17:39
Bonlenfum
20.4k3 gold badges60 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
And I want the output like this
Just outputting it that way is simply an of slicing:
import numpy as np
x = np.array([0, 1, 2, 3, 4, 5])
for i in range(1,len(x) + 1):
print(x[1:i])
Comments
lang-py