• Register
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.

12 7 7
15,250 points

Please log in or register to answer this question.

2 Answers

2 votes

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!

13 9 6
94,260 points
0 votes

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.

10 6 4
31,120 points

Related questions

0 votes
1 answer 26 views
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.
asked Jan 6 Mashhoodch 13k points
1 vote
1 answer 5 views
5 views
Problem: Why I got the error : python too many indices for array
asked Mar 19 MUHAMMAD MUNEEB 83k points
0 votes
1 answer 36 views
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.
asked Mar 6 Wafa Abu Yousef 6.1k points
1 vote
1 answer 4.3K views
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.
asked Apr 21, 2020 Gavin 15.3k points
0 votes
1 answer 39 views
39 views asked Oct 23, 2020 Shaad Sh 800 points
1 vote
1 answer 27 views
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.
asked Jun 30, 2020 adamSw 11.3k points
0 votes
1 answer 6 views
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
asked Mar 24 ummesalma 27.2k points
0 votes
1 answer 24 views
24 views
Problem: valueerror: sequence too large; cannot be greater than 32
asked Feb 24 Ethan ross 2.7k points
1 vote
1 answer 250 views
250 views
Problem : How to concatenate following numpy arrays? First np.array with the shape (5,4) as below : [[ 7487 500 389580 0] [ 7488 501 392994 0] [ 7491 508 389247 0] [ 7491 508 389247 0] [ 7492 502 399013 0]] Second np.array with the shape (1, ... ([array1, array2]) but i get below error ValueError: all the input arrays must have same number of dimensions How can I get the required output?
asked Dec 12, 2019 alecxe 7.5k points
0 votes
1 answer 94 views
94 views
Problem indexerror: arrays used as indices must be of integer (or boolean) type
asked Feb 11 charles mathews 5.5k points