haq
haq

Reputation: 469

Numpy array manipulation

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.

Upvotes: 1

Views: 370

Answers (2)

Solkar
Solkar

Reputation: 1226

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

Upvotes: 0

Bonlenfum
Bonlenfum

Reputation: 20155

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

Upvotes: 1

Related Questions