user_005
user_005

Reputation: 45

How to access specific row of multidimensional NumPy array with different dimension?

I have a NumPy array with two dimensions so that first array are numbers from 1 to 50 and second 50 to 150:

a =numpy.array([[1,2,3,...,50],[50,51,52...,150]]).

I want to print only specified row for example second row by means of

print(a[1,:]),

to get [50,51,52...,150] however it shows

    print((a[1,:]))
IndexError: too many indices for array  

error. When I reduced second row to the same number of elements as the first one, it works. So, the problem is printing specified row with different dimension. If possible, could you tell how to deal with this, please ? Thanks!

Upvotes: 2

Views: 3315

Answers (2)

hpaulj
hpaulj

Reputation: 231615

With a different number of elements in the 2 parts, you don't get a 2d array:

In [15]: a1=list(range(1,6))
In [16]: a2=list(range(5,16))
In [17]: a=np.array([a1,a2])
In [18]: a
Out[18]: array([[1, 2, 3, 4, 5], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]], dtype=object)
In [19]: a[1]
Out[19]: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In [20]: a.shape
Out[20]: (2,)

Note the dtype. It's object. a is a 2 element array, containing 2 lists. It is, for most purposes just a list of your two original lists, and has to be indexed in the same way:

In [21]: [a1,a2]
Out[21]: [[1, 2, 3, 4, 5], [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]

If the 2 components have the same length, the np.array does construct a 2d array.

When you have problems like this, check the shape and dtype. It's dangerous to just assume these properties. Print them out. And be wary of mixing list or arrays of different length with numpy. It works best with data that fits a neat regular multidimensional structure.

Upvotes: 2

Pankaj
Pankaj

Reputation: 517

It does not make sense to have different number of elements in different rows of a same matrix. To work around your problem, it is better to first fill all the missing elements in rows with 0 or NA so that number of elements in all rows are equal.

Please also look at answers in Numpy: Fix array with rows of different lengths by filling the empty elements with zeros. I am implementing one of the best solutions mentioned there for your problem.

import numpy as np
def numpy_fillna(data):

    lens = np.array([len(i) for i in data])
    mask = np.arange(lens.max()) < lens[:,None]

    out = np.zeros(mask.shape, dtype=data.dtype)
    out[mask] = np.concatenate(data)
    return out

a =np.array([range(1,50),range(50,150)])
data=numpy_fillna(a)

print data[1,:]

Upvotes: 0

Related Questions