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

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)

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)

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]