Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 634
K. Kovalev Avatar asked Apr 17 '16 18:04

K. Kovalev


People also ask

What does it mean only size 1 arrays can be converted to Python scalars?

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. You can skip the definition of f(x) and just pass the function int to the vectorize function: f2 = np.

Can only convert an array of size 1 to a scalar?

Only Size 1 Arrays Can Be Converted To Python Scalars Error is a typical error that appears as a TypeError form in the terminal. This error's main cause is passing an array to a parameter that accepts a scalar value. In various numpy methods, acceptable parameters are only a scalar value.


2 Answers

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.

If you look at the call signature of np.int, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize:

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() 

You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.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).

like image 119
ayhan Avatar answered Oct 04 '22 13:10

ayhan


Use:

x.astype(int) 

Here is the reference.

like image 31
FFT Avatar answered Oct 04 '22 11:10

FFT