Typeerror: Only size-1 arrays

In this post, we will learn how to solve the most common error of Python Programming Language which is typeerror: only size-1 arrays can be converted to python scalars. The main cause behind this error is that while providing a parameter to this one need to pass an integer value. Sometimes instead of an integer user passes an array as an argument which causes this error on their screen.

 

 

 

Solution of  typeerror: only size-1 arrays can be converted to Python scalars

The built-in int, which is deprecated in numpy version 1.20, was referred to as np.int. The parameter for int must be a scalar, as it does not accept objects that resemble arrays. Below is an example of the same:

 

# importing modules 
import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return int(x)
# calling vectorized function to pass an array
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)

# plotting the plot
plt.plot(x, f2(x))
plt.show()

 

 

Output

 

Here we are using the np.vectorize() function which is an in-built function in the numpy library. This function allows the user to pass an array as a  value instead of a single integer value. 

The matplotlib library is used here for plotting the graph. One point one should keep in mind while using np.vectorize() function is that it does not work over arrays of large lengths. This function normally acts as for loop. 

 

 

Also Read: Exact Value of Trig Functions

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *