Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
March 13th, 2005, 12:43 AM
 fupduck
Registered User

Join Date: Feb 2005
Posts: 4
Time spent in forums: 1 h 16 m 38 sec
Reputation 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
March 13th, 2005, 04:54 AM
 DevCoach
Contributing User

Join Date: Feb 2004
Location: London, England
Posts: 1,585
Time spent in forums: 2 Weeks 4 Days 2 h 58 m 23 sec
Reputation Power: 1372
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
March 14th, 2005, 01:47 AM
 Zone
Contributing User

Join Date: Jan 2005
Posts: 37
Time spent in forums: 1 Day 2 h 30 m 30 sec
Reputation Power: 9
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

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Array slicing with numarray