简体   繁体   中英

"IndexError: too many indices for array" for 1D numpy array

Somehow I do not understand the error message I am getting:

IndexError: too many indices for array

I have looked into other questions with that title but none seem to apply to my situation. This is my code.

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.array(max_len)
    for i in range(1, max_len):
        ret[i] = array[max_len - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

I do give only an integer value as the index. What am I missing?

The statement

ret = np.array(max_len)

is not returning the desired empty array, because of that you are getting this error

This should work

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.zeros(max_len)
    for i in range(1, max_len):
        ret[i] = array[max_len - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

Output

[0. 4. 3. 2.]

Another way to create empty array in numpy

ret = np.empty(shape=(max_len))

Here you are trying to reverse the input array, but above logic has some problems, below code should reverse the array

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.zeros(max_len)
    for i in range(0, max_len):
        ret[i] = array[max_len - 1 - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

Output

[4. 3. 2. 1.]

First of all, as anuragal answers, if you pass an integer to np.array , an array of that length is not created. For that, you have to use something like np.zeros or np.empty and pass in an array shape (which in your case, is simply one integer, so a 1-D array will be created). Always read the docs to understand how functions work.

Secondly, since it seems like you are trying to reverse an array, (the hard way, using loops!) numpy arrays start with the index 0: so you need to run that loop starting at zero.

Thirdly, if reversing this way is not purely out of academic interest, array[::-1] does the job. How does it work? Read this document on indexing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM