only size-1 arrays can be converted to Python scalars

Python

I have such Python code:

import numpy as np 

import matplotlib.pyplot as plt 

def f(x): 

return np.int(x) 

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

plt.plot(x, f(x)) 

plt.show()

And such error:

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

How can I fix it?

2
Answers

Replies

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 course page for more information, where you can find the Python tutorials and Python frequently asked interview questions and answers as well.

 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.