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

Total
0
Shares

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?


Solution

The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.

np.int was an alias for the built-in int, which is deprecated in numpy v1.20. The argument for int should be a scalar and it does not accept array-like objects. In general, if you want to apply a function to each element of the array, you can use np.vectorize:

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()

You can skip the definition of f(x) and just pass the function int to the vectorize function: f2 = np.vectorize(int).

Note that np.vectorize is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int) as @FFT suggests).

Source: StackOverflow.com

Leave a Reply

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