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

We get this error generally while working with NumPy and Matplotlib. If you have a function that accepts a single value, but if you pass an array instead, you will encounter TypeError: only size-1 arrays can be converted to python scalars.

In this tutorial, we will learn what is TypeError: only size-1 arrays can be converted to python scalars and how to resolve this error with examples.

What is TypeError: only size-1 arrays can be converted to python scalars?

Python generally has a handful of scalar values such as int, float, bool, etc. However, in NumPy, there are 24 new fundamental Python types to describe different types of scalars. 

Due to this nature, while working with NumPy, you should ensure to pass a correct type, else Python will raise a TypeError.

Let us take a simple example to reproduce this error. 

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value


def my_function(x):
    return int(x)

data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, my_function(data))
plt.show()

Output

Traceback (most recent call last):
  File "c:\Personal\IJS\Code\main.py", line 14, in <module>
    plt.plot(data, my_function(data))
  File "c:\Personal\IJS\Code\main.py", line 9, in my_function
    return int(x)
TypeError: only size-1 arrays can be converted to Python scalars

In the above example, we have an int function that accepts only single values. However, we are passing an array to the np.int() or int() method, which will not work and results in TypeError.

How to fix TypeError: only size-1 arrays can be converted to python scalars?

There are two different ways to resolve this error. Let us take a look at both solutions with examples.

Solution 1 – Vectorize the function using np.vectorize

If you are working with a simple array and then vectorizing, this would be the best way to resolve the issue.

The int() accepts a single parameter and not an array according to its signature. We can use np.vectorize() function, which takes a nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.

Behind the scenes, it’s a for loop that iterates over each array element and returns a single NumPy array as output.

Let us modify our code to use the np.vectorize() method and run the program.

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value

def my_function(x):
    return int(x)


# vectorize the function
f = np.vectorize(my_function)

data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, f(data))
plt.show()

Output

We can see that error is gone, the vectorize() function will loop through the array and returns a single array that is accepted by the int() function.

Image 9
TypeError: only size-1 arrays can be converted to python scalars 3

Solution 2 – Cast the array using .astype() method

The np.vectorize() method is inefficient over the larger arrays as it loops through each element.

The better way to resolve this issue is to cast the array into a specific type (int in this case) using astype() method.

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value


def my_function(x):
    # csat the array into integer
    return x.astype(int)


data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, my_function(data))
plt.show()

Output

Only Size-1 Arrays Can Be Converted To Python Scalars
TypeError: only size-1 arrays can be converted to python scalars 4

Conclusion

We get TypeError: only size-1 arrays can be converted to python scalars if we pass an array to the method that accepts only scalar values.

The issue can be resolved by using np.vectorize() function a nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.

Another way to resolve the error is to use the astype() method to cast the array into an integer type.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
How To Reverse A String In Python

How to Reverse a String in Python

Table of Contents Hide Reverse a string in PythonUsing extended slice operatorUsing for loopUsing while loopUsing recursionUsing reversed() method Python has many functions for string manipulation. However, the Python string…
View Post
Python String Capitalize()

Python String capitalize()

Table of Contents Hide capitalize() Syntaxcapitalize() ParameterReturn Value from capitalize()Example: Capitalize a string in Python Python string capitalize() method will convert the first letter in a string to uppercase and keep…
View Post
How To Copy A File In Python

How to Copy a File in Python?

Table of Contents Hide Modules to copy a file in Python shutil module top copy a file in Pythoncopy() copy2() copyfile() copyfileobj()os module to copy a file in Pythonpopen() system() subprocess…
View Post