[Solved] TypeError: Only Size-1 Arrays Can Be Converted To Python Scalars Error

Python has helped thousands of communities to create solutions for their real-life problems. With thousands of useful modules, Python has proved to be one of the top versatile languages in the coding world. In addition, writing in Python is similar to writing in English, and using it is even simpler. With simple single command module installs, you can install almost every dependency to control your problems. Numpy is one of those important modules, and Only Size 1 Arrays Can Be Converted To Python Scalars Error appears while using this module.

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. Hence, if you pass a single dimensional array or multidimensional array in the method, it’ll throw this error. With increasing methods accepting a single parameter, you can expect this error to appear many times.

This post will guide you with the causes of the error and it’s solutions.

What is Only Size 1 Arrays Can Be Converted To Python Scalars Error?

Only Size 1 Arrays Error is a TypeError that gets triggered when you enter an array as a parameter in a function or method which accepts a single scalar value. Many functions have inbuilt error handling methods to avoid crashing programs and validate the inputs given for the function. Without the validation, the python program will crash immediately, which can cause issues.

numpy.int() and numpy.float() shows this error due to single-valued parameters. As TypeError originates from an invalid data type, you can get this error by sending an array as a parameter.. There are different ways to avoid this error, which we’ll discuss in the post’s bottom section.

Why do I get Only Size 1 Arrays Can Be Converted To Python Scalars Error?

Errors are an integral part of the programming, and they should be handled properly. With the management of error handling, your program can not only avoid harmful vulnerabilities, but it can also perform in a better way. As a result, you can get the Only Size 1 Arrays error while using numpy. This module’s developers have categorized this error into TypeError, which describes that you supplied the wrong data to the function/method.

Causes of Only Size 1 Arrays Can Be Converted To Python Scalars Error

There are several ways the error can appear while using numpy. All of these errors are solvable by one or the other means. This error is a user sided error and passing appropriate parameters can prevent this error. Following are the causes of this error –

Incorrect Datatype

In Python, every data type has different methods and attributes. Each of these data types has different usage. In many numpy methods, the primary parameter required is a single value. With such methods, if you pass a numpy array as a parameter, Only Size 1 Arrays Can Be Converted To Python Scalars Error can appear.

Example:

import numpy as np

x = np.array([1, 2, 3, 4])
x = np.int(x)

Output:

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

Explanation:

In the program, x is a simple array with integer elements. If you try to convert this array into int form, it will throw an error because np.int() accept a single value.

Using Single Conversion Function

Single Conversion Functions are the functions that accept a single-valued datatype and convert it to another data type. For example, converting a string to int is a single-valued conversion. In numpy, these functions accept the single numpy element and change its datatype from within. If you pass a numpy array as a parameter, you’ll get an error in such methods.

Example –

import numpy as np

x = np.array([1, 2, 3, 4])
x = np.float(x)

Output –

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

Explanation –

In the above example, we wanted to convert all the integers from the numpy array to float values. np.float() throws TypeError as it accepts single-valued parameters.

Solutions for Only Size 1 Arrays Can Be Converted To Python Scalars Error

There are multiple ways of solving the TypeError in Python. Most importantly, Numpy modules provide some inbuilt functions which you can use to create a suitable datatype before using it in a method. Following are the solutions to this error –

1. Using Numpy Vectorize Function

In layman’s terms, Vectorize means applying an algorithm to a set of values rather than applying them on a single value. As the TypeError occurs due to its usage on sets of values, you can use numpy.vectorize() in between the algorithm and methods. This method acts like a python map function over a numpy array.

Code –

import numpy as np

vector = np.vectorize(np.float)
x = np.array([1, 2, 3])
x = vector(x)
print(x)

Output –

[1. 2. 3.]

Explanation –

Firstly, we started by creating a vector that accepts np.float as a parameter. To apply a method on all the numpy array elements, we’ll use this vector. Nextly, we created a numpy array and then used our vector() to apply np.float over all the values. This method avoids all sorts of TypeError and also converts all the values into the float.

2. Using Map() Function

Surely, the map is the basic inbuilt function in python that applies a function over all array elements. map() function accepts two major parameters. The first one is the function you need to apply over sets of values. The second one is an array that you want to change. Let’s jump on an example –

Code –

import numpy as np

x = np.array([1, 2, 3])
x = np.array(list(map(np.float, x)))
print(x)

Output –

[1. 2. 3.]

Explanation –

Firstly, we’ve created a simple integer array and used map(np.float, x) to convert all the elements from numpy array to float. As the map function returns a map object, we need to convert it back to the list and numpy array to restore its datatype. By using this method, you can avoid getting TypeError.

3. Using Loops

Loops are the most brute force methods to apply a function over a set of values. But it provides us control over all parts of the elements and can be used to customize elements if we need.

Code –

import numpy as np

x = np.array([1, 2, 3])
y = np.array([None]*3)
for i in range(3):
    y[i] = np.float(x[i])
print(y)

Output –

[1.0 2.0 3.0]

Explanation –

In the above example, we’ve used indexing to fetch the initial integer from the numpy array. Then applied the np.float() method to convert it from float to int. Furthermore, we’ve created a dummy numpy array y, which stores the float values after changing.

4. Using apply_along_axis

Apply_along_axis is a Numpy method that allows the users to apply a function over a numpy array along a specific axis. As numpy is looped according to axis number, you can use it to apply a function over sets of values.

Code –

import numpy as np

x = np.array([1, 2, 3])
app = lambda y: [np.float(i) for i in y]
x = np.apply_along_axis(app, 0, x)
print(x)

Output –

[1. 2. 3.]

Explanation –

In this example, we’ll use the lambda function to create a function’s vectorized function. Then we’ll use np.apply_along_axis to apply the lambda function over the specific numpy array. You can also specify the axis along which you need to apply the function.

plt.barh TypeError: Only size-1 arrays can be converted to Python scalars

plt.barh is a popular function that is used in Matplotlib to plot a horizontal bar graph. This function requires two arrays as input. The first one being the labels on Y-axis and the second one being the numeric values that are extended on the X-axis. In many cases, we try to convert the values of the list to integers by using np.int(). This issue creates a TypeError in the code as the list type of data cannot be converted into an int.

Error Example –

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 5))
plt.barh(np.array(["C", "C++", "Python"]), np.int(np.array(["10", "15", "20"])))
plt.show()

Possible Solution –

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 5))
plt.barh(np.array(["C", "C++", "Python"]), np.array(list(map(np.int, np.array(["10", "15", "20"])))))
plt.show()

Explanation –

Using map() function along with np.int will properly convert each value from str to integer in the array. This method can be used in plt.barh function to avoid TypeError.

Conclusion

Numpy module has provided thousands of useful methods that easily solve hard problems. These methods have their own sets of instructions and parameters that we need to follow properly. Only Size 1 Arrays Can Be Converted To Python Scalars Error appears when you provide an invalid data type to a function that accepts a scalar value. By following the solutions and alternatives given in the post, you can solve this error in no time!

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

1 3 votes
Article Rating
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ben
Ben
3 months ago
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

def asal(x):
    x=int(x)
    a=int(x**(1/2))
    if x==2:
        return None
    elif x==1:
        return False
    elif x==0:
        return False
    else:
        for i in range(2,a+1):
            if x%i==0:
                return False
                break
def asalliste(x,y):
    x=int(x)
    y=int(y)
    asallist=[]
    for i in range(x,y+1):
        if asal(i)!=False:
            print(i)
            asallist.insert(0,i)
    asallist.reverse()
    print(asallist)
    a = len(asallist)
    print(a)
    return a
t = np.arange(0.,10.,1)
# red dashes, blue squares and green triangles
plt.plot(t,int(asalliste(0,t)))
plt.show()


This code gives this error
 y=int(y)
TypeError: only size-1 arrays can be converted to Python scalars
Please help me

Edit:Asal means prime in Turkish

Last edited 3 months ago by Ben
Pratik Kinage
Admin
Pratik Kinage
3 months ago
Reply to  Ben

May I know, what are you trying to achieve?

The error is raised because y is an array and you cannot convert an array into an integer.

Krisna
Krisna
1 month ago
Reply to  Pratik Kinage

I have problem with kmean, can you email me? I want to give my data , I’m sorry my bad english

Pratik Kinage
Admin
Pratik Kinage
1 month ago
Reply to  Krisna

Yes,

Please send me your code at [email protected], I’ll check if it has any errors.

Regards,
Pratik