Only size-1 arrays can be converted to Python scalars

Deepanshu Bhalla Add Comment
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.
Solution : Only size-1 arrays can be converted to Python scalars

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

This error generally appears when Python expects a single value but you passed 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.

There are 5 method to solve this error

Solutions with examples

Create Reproducible Example

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)
TypeError: only size-1 arrays can be converted to Python scalars is deprecated alias so you can simply use int(x) but you will get the same error. It is because both and int(x) only accepts a single value not multiple values storing in an array. In other words you passed an array instead of scalar variable

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:
array([ 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 :

x = x.astype(int)

Solution 2 : Using np.vectorize()

Another possible solution is to use np.vectorize() instead of .astype(). But note that this is not efficient as compared to the prior solution.

convert2Integer = np.vectorize(int)

Solution 3 : Using map

By using map we can apply int() function over each array element. In map , we need to pass the two arguments - function and array which we want to convert.

np.array(list(map(int, x)))

Solution 4 : Using loop

It's easy to understand loop and you have flexibility over each element in terms of data manipulation. But it is not necessarily an efficient method. Also it involves writing extra lines of code which can be solved in a single line.

We created helper array y having similar length that array x has. Later we converted each element via int() function.

l = len(x)
y = np.array([None]*l)
for i in range(l):
    y[i] = int(x[i])


Solution 5 : Using apply_along_axis

Apply_along_axis lets you to apply int() to numpy array.

l = lambda y: [int(i) for i in y]
np.apply_along_axis(l, 0, x)
Another Example
Suppose you need to calculate log value of an array.

import numpy as np
import math

x = np.array([2, 3, 1])
TypeError: only size-1 arrays can be converted to Python scalars
This error occured because math.log(x) can only take one numeric value. Here you can use np.log(x)
array([0.69314718, 1.09861229, 0])
You can also fix it using np.vectorize(math.log). See the complete solution below.
logMultiple = np.vectorize(math.log)
Hope you understood now how to solve this error. The above solutions are intended to give you an idea how the problem can be solved in multiple ways but solution 1 is enough to solve your problem. If you have any question(s) regarding this error, please feel free to post in the comment section.
Related Posts
Spread the Word!
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 0 Response to "Only size-1 arrays can be converted to Python scalars"
Next → ← Prev