[Numpy-discussion] Slice and assign into new NDarray...
Anne Archibald
peridot.faceted@gmail....
Sat Mar 8 20:02:12 CST 2008
On 08/03/2008, Vince Fulco <vfulco1@gmail.com> wrote:
> I have an ND array with shape (10,15) and want to slice or subset(?) the data
> into a new 2D array with the following criteria:
>
> 1) Separate each 5 observations along axis=0 (row) and transpose them to
> the new array with shape (50,3)
>
>
> Col1 Co2 Col3
>
> Slice1 Slice2 Slice3
> ...
> ...
> ...
>
> Slice1 should have the coordinates[0:5,0], Slice2[0:5,1] and so
> on...I've tried initializing the target ND array with
>
> D = NP.zeros((50,3), dtype='int') and then assigning into it with
> something like:
>
> for s in xrange(original_array.shape[0]):
> D= NP.transpose([data[s,i:i+step] for i in range(0,data.shape[1], step)])
>
> with step = 5 but I get errors i.e. IndexError: invalid index
>
> Also tried various combos of explicitly referencing D coordinates but
> to no avail.
You're not going to get a slice - in the sense of a view on the same
underlying array, and through which you can modify the original array
- but this is perfectly possible without for loops.
First set up the array:
In [12]: a = N.arange(150)
In [13]: a = N.reshape(a, (-1,15))
You can check that the values are sensible. Now reshape it so that you
can split up slice1, slice2, and slice3:
In [14]: b = N.reshape(a, (-1, 3, 5))
slice1 is b[:,0,:]. Now we want to flatten the first and third
coordinates together. reshape() doesn't do that, exactly, but if we
swap the axes around we can use reshape to put them together:
In [15]: c = N.reshape(b.swapaxes(1,2),(-1,3))
This reshape necessarily involves copying the original array. You can
check that it gives you the value you want.
I recommend reading
http://www.scipy.org/Numpy_Functions_by_Category for all those times
you know what you want to do but can't find the function to make numpy
do it.
Anne
More information about the Numpy-discussion
mailing list