Translate

What error is "only integer scalar arrays can be converted to a scalar index"?

 I've come across another error that I often encounter over and over again while writing programs in python, so I thought I'd share it here.


When does only integer scalar arrays can be converted to a scalar index?



My personal experience is that the only integer scalar arrays can be converted to a scalar index error is one that I often see when using numpy or other methods to cut out a range of data.
In fact, I often get this error when using numpy to read a specific range of data from a pre-prepared array of data.

When you repeatedly cut out a range of data in a for loop, you can create an array outside the loop and read the data from that array.

Only integer scalar arrays can be converted to a scalar index is likely to occur if an int type is not specified when specifying a range of data

It seems to me that the only integer scalar arrays can be converted to a scalar index error occurs when you put an array in a place where you should put an integer. In fact, if you write code like this and get an error, you can often fix it by specifying an int type. Specifically

data = data[range1[1]:range1[2]]]

This way of writing a range specification can be replaced with the following
data = data[int(range1[1]):int(range1[1])]

I have a feeling that changing such a range specification to something like data = data[int(range1[1]):int(range1[1])] will prevent the occurrence of only integer scalar arrays can be converted to a scalar index.

As a side note, the same error can also occur when the contents of range1 are float type and contain a small number of values.

In such cases, rewriting it like this will further reduce the probability of the error occurring.
data = data[int(round(range1[1])):int(round(range1[1]))]

By rounding in advance using the round function, which is included in python, you can avoid including a decimal point when specifying arrays.