### Thread: Array slicing with numarray

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Feb 2005
Posts
4
Rep Power
0

#### Array slicing with numarray

I need to slice a 2D array at specific user defined values. Let's say the array is defined by:
Code:
```for i in arange(20):
for j in arange(20):
if i >= j:
A[i,j] = 1```
The user defines a list of numbers between 1 and 20 and with a length between 2 and 20. Something like this:

B = (4,8,12,16,20)

I need to have the final output have rows equal to length of list B (5 in this case) with 1's extending out to the values in B. Something like this:

C = [[1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0],....]

I'm thinking I probably don't need to setup A in the first place but I haven't come up with any other ideas. The process by which to do this is escaping me at this point. As always any help is greatly appreciated.
fd
2. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
London, England
Posts
1,585
Rep Power
1377
I don't know how to do it with numarray, but it is easy with regular Python lists:

Code:
```>>> B = (4,8,12,16,20)
>>> maxlen = max(*B)
>>> maxlen
20
>>> C = [ [1] * x + [0] * (maxlen-x) for x in B ]
>>> C
[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
>>>```
You can probably create this first then convert it to a numarray object.

Dave - The Developers' Coach
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Jan 2005
Posts
37
Rep Power
14
You definitely don't need to set up A in the first place. If you do set up A, though, it is pretty easy:

Code:
```from numarray import *

A = zeros([20,20])

for i in arange(20):
for j in arange(20):
if i >= j:
A[i,j] = 1

B = [3,7,11,15,19]

C = take(A,B)

print C```
if you don't set up A in advance, you could do it like this:

Code:
```from numarray import *

num_cols = 20

B = [3,7,11,15,19]

C = array(shape=(len(B),num_cols),type=Int32)

for i in range(0,len(B)):
C[i] = where(arange(num_cols) <= B[i],1,0)

print C```
note: remember that you can't use an offset of 20 in a 20x20 array... just like in a list offsets start at 0