Sunday, January 29, 2023
HomeData Analytics and VisualizationOnly size-1 arrays can be converted to Python scalars

# Only size-1 arrays can be converted to Python scalars

Numpy is one of the most used module in Python and it is used in a variety of tasks ranging from creating array to mathematical and statistical calculations. Numpy also bring efficiency in Python programming. While using numpy you may encounter this error TypeError: only size-1 arrays can be converted to Python scalars It is one of the frequently appearing error and sometimes it becomes a daunting challenge to solve it.

## Demystify : Only Size 1 Arrays Can Be Converted To Python Scalars Error

This error generally appears when Python expects a single value but you pass an array which consists of multiple values. For example : you want to calculate exponential value of an array but the function for exponential value was designed for scalar variable (which means single value). When you pass numpy array in the function, it will return this error. This error handling is to prevent your code to process further and avoids unexpected output from the function later.

## 5 Ways to solve the error

Passed an array instead of scalar variable

Let’s understand the issue with an example. Suppose you have an array consisting of decimals values and your manager asked you to convert it into integer.
Let’s create a numpy array having decimals (float)
import numpy as np
x = np.array([2, 3.5, 4, 5.3, 27])
Let’s convert to integer values (without decimals)np.int(x)

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

np.int() is deprecated alias so you can simply use int(x) but you will get the same error. It is because both np.int() and int(x) only accepts a single value not multiple values storing in an array.

Solution 1 : Using .astype() method

In order to convert a NumPy array of float values to integer values, we can instead use the following code: x.astype(int) Outputarray([ 2, 3, 4, 5, 27])3.5 and 5.3 from the original array has been converted to 3 and 5.

In order to reflect changes in x array, use the code below :

RELATED ARTICLES