Stripers247
Stripers247

Reputation: 2335

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.

Upvotes: 4

Views: 41987

Answers (3)

Dave cook
Dave cook

Reputation: 11

I have also struggled with this problem when parsing many input files that can have 1-1000s of rows. However, I am using numpy genfromtxt which doesn't allow you to set 'ndmin', so the solution I came up with is to manually set the array shape equal 1 for arrays with 1 row:

>>> arr=np.genfromtxt('file',names=['a','b'],dtype='f4,f4') 
>>> if (np.size(arr) == 1): arr.shape=1

The 1 row array now acts like a 1-D array that can be indexed:

>>> for i in range(np.size(arr)): print arr['a'][i]

Upvotes: 1

Alex Riley
Alex Riley

Reputation: 177048

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)

Upvotes: 11

rkp
rkp

Reputation: 438

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)

Upvotes: 6

Related Questions