only size-1 arrays can be converted to Python scalars

in Python
Python Tutorials
2 Answers to this question

Solution -
import numpy as np
import matplotlib.pyplot as plt
def custom_function(x):
return x.astype(int)
arr1= np.arange(1, 10, 0.5)
plt.plot(arr1, custom_function(arr1))
plt.show()
Detail Description - here


Your function is expecting a single value and you have passed an array instead. That is the reason you are getting this error. If you want to apply a function on each element of an array, you can use the vectorize method from numpy. Change your code to this.


import numpy as np

import matplotlib.pyplot as plt


def f(x):

return np.int(x)

f2 = np.vectorize(f)

x = np.arange(1, 15.1, 0.1)

plt.plot(x, f2(x))

plt.show()

 

If you want to unleash your potential in this competitive field, please visit the Python Training Certification page for more information, where you can find the       and    Python Interview Questions FAQ's and answers    as well.

For more updates on the latest courses stay tuned to HKR Trainings.

To Top