Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexError: too many indices. Numpy Array with 1 row and 2 columns

When I try to get just the first element of an array like this

import numpy

a = numpy.array([1,2])

a[:,0]

I get this error

---------------------------------------------------------------------------
 IndexError                                Traceback (most recent call last)
<ipython-input-3-ed371621c46c> in <module>()
----> 1 a[:,0]

IndexError: too many indices

I would like to find a way to do this while still using slicing because the full code opens and reads many different files using numpy.loadtxt() all having two columns which vary from 1 to some N.

like image 433
Stripers247 Avatar asked Dec 01 '22 14:12

Stripers247


2 Answers

Your array a = numpy.array([1,2]) only has one dimension: its shape is (2,). However, your slice a[:,0] specifies selections for two dimensions. This causes NumPy to raise the error.

To get the first element from a you only need to write a[0] (a selection for only one dimension is being made here).


Looking at your other question, if you want to ensure that the syntax a[:,0] always works, you could ensure that a always has two dimensions. When loading an array with np.loadtxt use the ndmin parameter, e.g.:

np.loadtxt(F, skiprows=0, ndmin=2)
like image 176
Alex Riley Avatar answered Dec 06 '22 10:12

Alex Riley


As mentioned above, you have a one-dimensional array and you're trying to slice it with two dimensions.

One thing to add, and which I've found very useful in the past, is that numpy allows you easily cast a 1D array into a 2D array (either as a row or column):

>>> a = np.array([0,1,2])
>>> a.shape
(3,)
>>> a_row = a[None,:]
>>> a_row.shape
(1,3)
>>> a_col = a[:,None]
>>> a_col.shape
(3,1)
like image 36
rkp Avatar answered Dec 06 '22 10:12

rkp