1

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.

1
  • 3
    You 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. Commented May 14, 2013 at 17:43

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

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.