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).
Related Posts:
- LogisticRegression: Unknown label type: ‘continuous’ using sklearn in python
- Syntax in Python (.T)
- Numpy/Python Array Value error
- Calculating Covariance with Python and Numpy
- Python reshape list to ndim array
- Python – TypeError: Object of type ‘int64’ is not JSON serializable
- How to implement the Softmax function in Python
- Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script
- Numpy float64 vs Python float
- Calculate the Cumulative Distribution Function (CDF) in Python
- Python can’t multiply sequence by non-int of type ‘float’
- TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array
- ImportError: DLL load failed: The specified module could not be found
- ValueError: setting an array element with a sequence
- ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
- What exactly does numpy.exp() do? [closed]
- numpy: Invalid value encountered in true_divide
- python numpy ValueError: operands could not be broadcast together with shapes
- ValueError: Unknown label type: ‘continuous’
- TypeError: unhashable type: ‘numpy.ndarray’
- How to fix IndexError: invalid index to scalar variable
- Could not install packages due to a “Environment error :[error 13]: permission denied : ‘usr/local/bin/f2py'”
- How does numpy.newaxis work and when to use it?
- Plotting a 2D heatmap with Matplotlib
- Should I use np.absolute or np.abs?
- What does numpy.random.seed(0) do?
- What does the c underscore expression `c_` do exactly?
- Convert pandas dataframe to NumPy array
- Unable to plot Double Bar, Bar plot using pyplot for ndarray
- Error: all the input array dimensions except for the concatenation axis must match exactly
- Singular matrix issue with Numpy
- How to find all occurrences of an element in a list
- TypeError: ‘numpy.float64’ object is not callable
- ‘DataFrame’ object has no attribute ‘sort’
- ValueError: all the input arrays must have same number of dimensions
- TypeError: cannot unpack non-iterable int objec
- ValueError: setting an array element with a sequence
- filename.whl is not a supported wheel on this platform
- Convert a tensor to numpy array in Tensorflow?
- How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)
- What is dtype(‘O’), in pandas?
- ‘End of statement expected’ in pycharm
- What does numpy.gradient do?
- How can the Euclidean distance be calculated with NumPy?
- ‘list’ object has no attribute ‘shape’
- Array of arrays (Python/NumPy)
- load csv into 2D matrix with numpy for plotting
- Purpose of `numpy.log1p( )`?
- Overcome ValueError for empty array
- index 1 is out of bounds for axis 0 with size 1
- Pytorch reshape tensor dimension
- Most efficient way to reverse a numpy array
- How to remove specific elements in a numpy array
- Overflow / math range error for log or exp
- Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?
- Overflow Error in Python’s numpy.exp function
- Simple plot in python of a numpy array?
- How to normalize a 2-dimensional numpy array in python less verbose?
- Insert some string into given string at given index in Python
- Understanding NumPy’s einsum
- For loop and ‘numpy.float64’ object is not iterable error
- What are the causes of overflow encountered in double_scalars besides division by zero?
- RuntimeWarning: divide by zero encountered in log
- How can I remove Nan from list Python/NumPy
- Python/Numpy MemoryError
- RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility
- Error NameError: name ‘np’ is not defined
- TypeError: Invalid dimensions for image data when plotting array with imshow()
- Numpy.dot TypeError: Cannot cast array data from dtype(‘float64’) to dtype(‘S32’) according to the rule ‘safe’
- NumPy array is not JSON serializable
- Does Numpy automatically detect and use GPU?
- How can I check whether a numpy array is empty or not?
- Moving average or running mean
- How to start from second index for for-loop
- Official abbreviation for: import scipy as sp/sc
- How to plot an array in python?
- How to create a numpy array of all True or all False?
- Removing nan values from an array
- LinAlgError: Last 2 dimensions of the array must be square
- Building multi-regression model throws error: `Pandas data cast to numpy dtype of object. Check input data with np.asarray(data).`
- ImportError in importing from sklearn: cannot import name check_build
- Root mean square of a function in python
- What are the differences between numpy arrays and matrices? Which one should I use?
- Concat DataFrame Reindexing only valid with uniquely valued Index objects
- mean, nanmean and warning: Mean of empty slice
- Replacing Pandas or Numpy Nan with a None to use with MysqlDB
- threshold in 2D numpy array
- How to normalize a NumPy array to within a certain range?
- Numpy Resize/Rescale Image
- numpy array concatenation error: 0-d arrays can’t be concatenated
- How to implement the ReLU function in Numpy
- RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
- Sorting arrays in NumPy by column
- How to install NumPy for Python 3.6
- numpy : calculate the derivative of the softmax function
- How to install numpy to Python 3.5?
- Conditional indexing with Numpy ndarray
- python numpy machine epsilon
- Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
- How to zip two 1d numpy array to 2d numpy array [duplicate]