How to Solve Python TypeError: only size-1 arrays can be converted to Python scalars

by | Programming, Python, Tips

If you attempt to pass a NumPy array with more than one element to the numpy.int() or numpy.float() functions, you will raise the TypeError: only size-1 arrays can be converted to Python scalars.

To solve this error, you can call the astype() method on the array to convert the array elements to integers. You can also use the built-in vectorize method.

This tutorial will go through the error and solve it with code examples.


What is a Python TypeError?

TypeError tells us that we are trying to perform an illegal operation for a specific Python data type.

What is a Scalar in Python?

In Python, scalar variables hold the basic building blocks of data: numbers and characters. Python scalars are singular values, and you cannot convert a sequence of size greater than one to a scalar.

TypeError: only size-1 arrays can be converted to Python scalars

The NumPy functions int() and float() take single-valued parameters. An array with more than one element is an invalid data type for these functions. We can use two functions in NumPy, astype() and vectorize(), to convert the elements in the array to the desired type. We will go through them in the following examples.

Example: Converting NumPy Array Elements to Integers

Let’s look at an example with a NumPy array of float and integer values. We want all the elements in the array to be integers. Let’s try to do this using the int() function:

import numpy as np

x = np.array([2, 3.5, 6, 7.3, 9, 10.1, 12])

np.int(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----≻ 1 np.int(x)

TypeError: only size-1 arrays can be converted to Python scalars

We raise the error because the array x has a size greater than one.

Solution #1: Using astype()

The first solution we can use is the astype() method, which belongs to the ndarray class. The astype() method returns a copy of the array with the elements cast to a specific type. Let’s look at the use of the astype() method:

x = np.array([2, 3.5, 6, 7.3, 9, 10.1, 12])

x_int = x.astype(int)

print(x_int)

We assign the array copy to the variable x_int and print it to the console. Let’s run the code to see the result:

[ 2  3  6  7  9 10 12]

The new array consists only of integers.

Solution #2: Using vectorize()

The second solution is the generalized function class vectorize(). This function class allows us to generate a vectorized function. The vectorized function evaluates a callable Python function or method over the elements in a numpy array. The vectorize() function class is similar to Python’s built-in map() function, which you can read more about in the article called: How to Use the Python Map Function.

Let’s look at how to use the vectorize() function:

x = np.array([2, 3.5, 6, 7.3, 9, 10.1, 12])

# Create the vector function with np.int() as a paramter

vector = np.vectorize(np.int)

x_int = vector(x)

print(x_int)

Our vector function applies np.int() to all elements in the array. Let’s run the code to get the result:

[ 2  3  6  7  9 10 12]

The new array consists only of integers.

Summary

Congratulations on reading to the end of this tutorial! If you try to convert a numpy array with a size greater than one to an integer or a float, you will raise the error: TypeError: only size-1 arrays can be converted to Python scalars. You can call the astype() method from the array or define a vectorize() function and apply it to the array to solve the error.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee