How to Fix: only integer scalar arrays can be converted to a scalar index


One error you may encounter when using Python is:

TypeError: only integer scalar arrays can be converted to a scalar index

This error usually occurs for one of two reasons:

1. You attempted to perform array indexing on a list.

2. You attempted to concatenate two matrices using incorrect syntax.

The following examples shows how to avoid these errors in both scenarios.

Example 1: You attempted to perform array indexing on a list.

Suppose we attempt to use the following code to create a line chart in matplotlib with a legend and labels:

import numpy as np

#create a list of values
data = [3, 5, 5, 7, 8, 10, 12, 14]

#choose 3 random values from list
random_values = np.random.choice(range(len(data)), size=2)

#attempt to use indexing to access elements in list
random_vals = data[random_values.astype(int)]

#view results
random_vals

TypeError: only integer scalar arrays can be converted to a scalar index

We receive an error because we attempted to use array indexing on a list.

To avoid this error, we must first convert the list to a NumPy array by using np.array() as follows:

import numpy as np

#create a list of values
data = [3, 5, 5, 7, 8, 10, 12, 14]

#choose 3 random values from list
random_values = np.random.choice(range(len(data)), size=2)

#attempt to use indexing to access elements in list
random_vals = np.array(data)[random_values.astype(int)]

#view results
random_vals

array([5, 7])

This time we’re able to randomly select two values from the list without any errors since we first converted the list to a NumPy array.

Example 2: You attempted to concatenate two matrices using incorrect syntax.

Suppose we attempt to use the following code to concatenate two NumPy matrices together:

import numpy as np

#create twoNumPy matrices
mat1 = np.matrix([[3, 5], [5, 7]])
mat2 = np.matrix([[2, 4], [1, 8]])

#attempt to concatenate both matrices
np.concatenate(mat1, mat2)

TypeError: only integer scalar arrays can be converted to a scalar index

We receive an error because we failed to supply the matrices in the form of a tuple to the concatenate() function.

To avoid this error, we must use double parenthesis to supply the matrices in the form of a tuple to the concatenate() function as follows:

import numpy as np

#create twoNumPy matrices
mat1 = np.matrix([[3, 5], [5, 7]])
mat2 = np.matrix([[2, 4], [1, 8]])

#attempt to concatenate both matrices
np.concatenate((mat1, mat2))

matrix([[3, 5],
        [5, 7],
        [2, 4],
        [1, 8]])

This time we’re able to concatenate the two matrices without any error.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Leave a Reply

Your email address will not be published.