user5433002
user5433002

Reputation:

Indexing an array inside an array

I have an array inside an array. Normal array indexing fails to work in this case . One way i can solve this problem is that I can convert 'a' into list and then again convert it into an array --a two step process but i want to know is there any other way to slice it so that the structure of 'a' remains unchanged ?

a=np.array([[np.arange(3)],[np.arange(6,9)],[np.arange(11,14)]])
array([[[ 0,  1,  2]],

       [[ 6,  7,  8]],

       [[11, 12, 13]]])

a.shape
(3L, 1L, 3L)

a.ndim
3

type(a)
numpy.ndarray

Please help me on this.

Upvotes: 1

Views: 138

Answers (2)

hpaulj
hpaulj

Reputation: 231385

Compare your 2 arrays:

In [39]: a=np.array([[np.arange(3)],[np.arange(6,9)],[np.arange(11,14)]])
In [40]: a1=np.array([np.arange(3),np.arange(6,9),np.arange(11,14)])
In [41]: a
Out[41]: 
array([[[ 0,  1,  2]],

       [[ 6,  7,  8]],

       [[11, 12, 13]]])
In [42]: a.shape       
Out[42]: (3, 1, 3)      # 3d
In [43]: a1
Out[43]: 
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [11, 12, 13]])
In [44]: a1.shape
Out[44]: (3, 3)     # 2d

One way to remove the size 1 dimension is with squeeze:

In [45]: np.squeeze(a)
Out[45]: 
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [11, 12, 13]])

or reshape:

In [46]: a.reshape(3,3)
Out[46]: 
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [11, 12, 13]])

You treat the 3 dimensions of a in exactly the same was the 2 of a1:

In [47]: a1[1,:]
Out[47]: array([6, 7, 8])      # index 1 dim of the 2
In [48]: a[1,:]
Out[48]: array([[6, 7, 8]])    # index 1 dim of the 3
In [49]: a[1,0,:]
Out[49]: array([6, 7, 8])      # index 2 dim of the 3

Upvotes: 1

Patrick Trentin
Patrick Trentin

Reputation: 7342

Perhaps you have an unnecessary level of nesting there, in case you can initialize your array like this

a=np.array([np.arange(3),np.arange(6,9),np.arange(11,14)])

then you can access its elements with standard notation

a[1,1]

If the level of nesting is not incorrect, then you can still access a's elements like this:

a[1,0,1]

Basically, the problem is that you are wrapping the second-level array inside another array of dimension 1, so when you access its elements you need to keep in mind that.

Upvotes: 1

Related Questions