Online Tutorials & Training Materials | STechies.com
Register Login

TypeError: Only Size-1 Arrays Can be Converted to Python Scalars

|| 0

TypeError: Only Size-1 Arrays Can be Converted to Python Scalars
Stechies

When we define such function which can accept a single value but we are passing an array, in this case we will get this type error ‘only size-1 arrays can be converted to python scalars’.

Example:

# import numpy & matplotlib
import numpy
import matplotlib.pyplot 

# define your custome function
def myfunction(x): 
    return numpy.int(x)

#
#myfunction2 = numpy.vectorize(myfunction)

x = numpy.arange(1, 15.1, 0.1) 
matplotlib.pyplot.plot(x, myfunction(x))
matplotlib.pyplot.show()

Output:

Traceback (most recent call last):
  File "error-1.py", line 13, in <module>
    matplotlib.pyplot.plot(x, myfunction(x))
  File "error-1.py", line 7, in myfunction
    return numpy.int(x)
TypeError: only size-1 arrays can be converted to Python scalars

Solution:

As you can see in the above example we have called single int(x) value in the function and for value of ‘x’ we are passing an array that is the reason we are getting this type error.

To fix this error we can use numpy.vectorize() function to convert an array in to vector.

# import numpy & matplotlib
import numpy
import matplotlib.pyplot 

# define your custome function
def myfunction(x): 
    return numpy.int(x)

myfunction2 = numpy.vectorize(myfunction)
x = numpy.arange(1, 15.1, 0.1) 
matplotlib.pyplot.plot(x, myfunction(x))
matplotlib.pyplot.show()

Output:

only size-1 arrays can be converted to python scalars

TypeError: only integer scalar arrays can be converted to a scalar index

Example: 

# import numpy
import numpy

# Create array
ar1 = numpy.array(['Red', 'Blue', 'Green', 'Orange'])
ar2 = numpy.array(['Black', 'Yellow'])

# Concatenate array ar1 & ar2
ar3 = numpy.concatenate(ar1, ar1)
print(ar3)

Output:

Traceback (most recent call last):
  File "error-1.py", line 9, in <module>
    ar3 = numpy.concatenate(ar1, ar1)
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

Solution:

To solve this error you need to convert array 1 and array 2 in to tuple.

# import numpy
import numpy

# Create array
ar1 = numpy.array(['Red', 'Blue', 'Green', 'Orange'])
ar2 = numpy.array(['Black', 'Yellow'])

# Concatenate array ar1& ar2
ar3 = numpy.concatenate((ar1, ar1))
print(ar3)

Output:

['Red' 'Blue' 'Green' 'Orange' 'Red' 'Blue' 'Green' 'Orange']