Only length-1 arrays can be converted to python scalars

Total
0
Shares
Only length-1 arrays can be converted to python scalars

Numpy throws error – only length-1 (size-1) arrays can be converted to python scalars when you are passing an array to a Python inbuild function which expects single value. This could happen with int(), float(), bytes() etc. Get whole list of scalar types here.

Note: Some articles suggest that it’s a matplotlib error but it is not. Neither it has anything to do with it. It’s a Python error raised by passing wrong arguments to a function.

Problem

Problem is that you are passing an array of length > 1 to a function like int(), which expect single digit. So, this will generate the error –

arr = [1, 2, 3.4, 5.6, "8"]

print(int(arr))

Error: only length-1 arrays can be converted to python scalars

Solution

Simple, don’t pass an array. Pass a single value. Or, you may pass a single value array. i.e. an array of length 1.

First of all we need to understand our use case. Why we are passing an array to int() or float()? Most probably you want to convert the type of each value of array. For example, converting all string or float values in array to int. Like this –

arr = [1, 2, 3.4, 5.6, "8"]

// convert to [1, 2, 3, 5, 8]

If you pass this arr to int() function, you will get only length-1 (size-1) arrays can be converted to python scalars error.

So how to convert it? There are two solutions –

  1. Loop over each value of array and convert into int().
  2. Use vectorize() function of numpy.

Solution 1: Using Loop

arr = [1, 2, 3.4, 5.6, "8"]

for index in range(len(arr)):
    arr[index] = int(arr[index])

print(arr)

# Output: [1, 2, 3, 5, 8]

Here I am using a for loop to access individual values of array. Then we are type casting each value to int and store them back to the array.

Solution 2: Using numpy vectorize()

If you are using numpy then you can use it’s vectorize() function. Internally it runs a loop over each value of the array and do computations according to provided function. So, it accepts array and a custom function.

import numpy as np

arr = [1, 2, 3.4, 5.6, "8"]

def myfunc(a):
    return int(a)

vectorfunc = np.vectorize(myfunc)

print(vectorfunc(arr))

# Output: [1, 2, 3, 5, 8]

      This is the best article on only length-1 arrays can be converted to python scalars ♥♥

Click here to Tweet this

Conclusion

Sometimes lenient languages like Python and Php could be strict too. Especially when you are breaking the rules. In this case, we were doing the same. Passing an array to int() which could only handle single value. Resulting in only length-1 (size-1) arrays can be converted to python scalars error. But we saw that we can very easily solve this by running loop over each item or by using numpy vectorize function.

Live Demo

Open Live Demo