TypeError: only integer arrays with one element can be converted to an index 3

Question:

I’m having this error in the title, and don’t know what’s wrong. It’s working when I use np.hstack instead of np.append, but I would like to make this faster, so use append.

time_list a list of floats

heights is a 1d np.array of floats

j = 0
n = 30
time_interval = 1200
axe_x = []

while j < np.size(time_list,0)-time_interval:
    if (not np.isnan(heights[j])) and (not np.isnan(heights[j+time_interval])):
        axe_x.append(time_list[np.arange(j+n,j+(time_interval-n))])

 File "....", line .., in <module>
    axe_x.append(time_list[np.arange(j+n,j+(time_interval-n))])

TypeError: only integer arrays with one element can be converted to an index
Asked By: GeoffreyB

||

Answers:

The issue is just as the error indicates, time_list is a normal python list, and hence you cannot index it using another list (unless the other list is an array with single element). Example –

In [136]: time_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]

In [137]: time_list[np.arange(5,6)]
Out[137]: 6

In [138]: time_list[np.arange(5,7)]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-138-ea5b650a8877> in <module>()
----> 1 time_list[np.arange(5,7)]

TypeError: only integer arrays with one element can be converted to an index

If you want to do that kind of indexing, you would need to make time_list a numpy.array. Example –

In [141]: time_list = np.array(time_list)

In [142]: time_list[np.arange(5,6)]
Out[142]: array([6])

In [143]: time_list[np.arange(5,7)]
Out[143]: array([6, 7])

Another thing to note would be that in your while loop, you never increase j, so it may end-up with infinite loop , you should also increase j by some amount (maybe time_interval ?).


But according to the requirement you posted in comments –

axe_x should be a 1d array of floats generated from the time_list list

You should use .extend() instead of .append() , .append would create a list of arrays for you. But if you need a 1D array, you need to use .extend(). Example –

time_list = np.array(time_list)
while j < np.size(time_list,0)-time_interval:
    if (not np.isnan(heights[j])) and (not np.isnan(heights[j+time_interval])):
        axe_x.extend(time_list[np.arange(j+n,j+(time_interval-n))])
        j += time_interval           #Or what you want to increase it by.
Answered By: Anand S Kumar
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.