# Indexerror: too many indices for array

1 vote
647 views

## Problem:

Hello guys,

Well, I am working with a NumPy array after learning the array a little bit. I am trying to print a particular element from each row from a two-dimensional array. While I am trying to run the program it returns an error Indexerror: too many indices for array

Why I am getting this error? Do you guys have any idea about this? I am attaching my sample code snippet below:

>>> n = np.array([[1,2,3], [5,6,7], [9,10,11,12]])
>>> n[: , 2]

Above the program is producing the error below:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array

What’s wrong with this and how may I get rid of this? I am looking forward to hearing back from you guys.

Thanks a lot.

## Solution:

This too many indices for array error is an IndexError in python. It means you did something wrong on indexing an array in your program. NumPy arrays are meant to be an equal length of arrays. In your program, you initialized a two-dimensional array that doesn’t have the same length that’s the reason it encounters the error. All you need to resize the length or print the array as a list.

And you may want to do this:

>>> n = np.array([[1,2,3], [5,6,7], [9,10,11,12]])
>>> print(n)
[list([1, 2, 3]) list([5, 6, 7]) list([9, 10, 11,12])]
>>> print(type(n))

Give it a try and post your feedback here and you must read the NumPy documentation from here

Thanks and Good Day!

## Solution:

The problem is idx has shape (11303402,1) because the logical comparison returns an array of the same shape as labels. These two dimensions use all of the indexes in features. The quick work around is

Xt=features[idx[:,0],:]

### I think the problem is given in the error message, although it is not very easy to spot:

IndexError: too many indices for array
xs  = data[:, col["l1"     ]]

### Explanation:

'Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None).

This is a bit of a guess - I wonder if one of the filenames you pass to loadfile() points to an empty file, or a badly formatted one? If so, you might get an array returned that is either 1D, or even empty (np.array(None) does not throw an Error, so you would never know...). If you want to guard against this failure, you can insert some error checking into your loadfile function.

### I highly recommend in your for loop inserting:

print(data)

This will work in Python 2.x or 3.x and might reveal the source of the issue. You might well find it is only one value of your outputs_l1 list (i.e. one file) that is giving the issue.

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

### If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
npy_intp n, i;
n = PyTuple_GET_SIZE(index);
if (n > result_n) {
PyErr_SetString(PyExc_IndexError,
"too many indices for array");
return -1;
}
for (i = 0; i < n; i++) {
result[i] = PyTuple_GET_ITEM(index, i);
Py_INCREF(result[i]);
}
return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

## Related questions

26 views
Problem: I know there is a ton of these threads but all of them are for very simple cases like 3x3 matrices and things of that sort and the solutions do not even begin to apply to my situation. So I'm trying to graph G versus l1 (that's not an eleven, but an ... 250 data points. I had another user (shout out to Hugh Bothwell!) help me with an error in my code, but now another error has surfaced.
1 vote
5 views
Problem: Why I got the error : python too many indices for array
36 views
Problem: What is the solid reason behind it, and how can I fix the error? Please help to get rid of this. I appreciate your concern: Indexerror: invalid index to scalar variable.. Thanks.
1 vote
4.3K views
Problem: I have a text file that contains a matrix of [2][2] and I am trying to open it in my python program and store the values as integers in a variable. Further, I tried to add some more operations with those values. For better understanding you may check my ... is the solid reason behind it, and how can I fix the error? Please help to get rid of this. I appreciate your concern. Thanks.
39 views
1 vote
27 views
Problem: Hello Kodlogs, I am a new student in Python. Previously I used to develop programs in Java. I just installed a fresh Python on my machine. A lot of things to know and learn in Python, and for that, I joined this forum. I found the forum very helpful with a lot of ... same thing, but I want to do it in a NumPy program. How do you do it? Could you please share me the tip? Thanks in advance.
6 views
Problem: I have an array of size 11 called 'wavelength' and a larger array of size n called 'MN'. And 'model' is an m by n array. and getting this as an error: File "test_prog.py", line 658, in <module> y=np.empty(model[MN][i],float) ValueError: sequence too large; must be smaller than 32