Only size 1 arrays can be converted to python scalars ошибка

Вам нужно использовать векторизированный аналог скалярной функции math.erfc — scipy.special.erfc, которая умеет работать с векторами:

from scipy.special import erfc

def a(x, t, D, Cs, C0):
    return ((Cs - C0)*erfc(((x*0.01)*0.01)/(2*((D*t)**0.5))) + C0)*100
C1 = a(x,t1,D,Cs,C0) 
fig, ax = plt.subplots()
ax.plot(x,C1)

введите сюда описание изображения

PS ваш вектор x состоит всего из двух элементов, поэтому и график такой…

In [161]: x = np.linspace(0, 0.5, 200)

In [162]: C1 = a(x,t1,D,Cs,C0)
     ...: fig, ax = plt.subplots()
     ...: ax.plot(x,C1)

введите сюда описание изображения

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.

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!

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться при использовании Python:

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

Эта ошибка возникает чаще всего, когда вы пытаетесь использовать np.int() для преобразования массива значений с плавающей запятой NumPy в массив целочисленных значений.

Однако эта функция принимает только одно значение вместо массива значений.

Вместо этого вы должны использовать x.astype(int) для преобразования массива значений с плавающей запятой NumPy в массив целочисленных значений, поскольку эта функция может принимать массив.

В следующем примере показано, как исправить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы создаем следующий массив значений с плавающей запятой NumPy:

import numpy as np

#create NumPy array of float values
x = np.array([3, 4.5, 6, 7.7, 9.2, 10, 12, 14.1, 15])

Теперь предположим, что мы пытаемся преобразовать этот массив значений с плавающей запятой в массив целочисленных значений:

#attempt to convert array to integer values
np.int (x)

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

Мы получаем TypeError , потому что функция np.int() принимает только отдельные значения, а не массив значений.

Как исправить ошибку

Чтобы преобразовать массив значений с плавающей запятой NumPy в целочисленные значения, мы можем вместо этого использовать следующий код:

#convert array of float values to integer values
x.astype (int)

array([ 3, 4, 6, 7, 9, 10, 12, 14, 15])

Обратите внимание, что массив значений был преобразован в целые числа, и мы не получаем никаких ошибок, поскольку функция astype() может обрабатывать массив значений.

Примечание.Полную документацию по функции astype() можно найти здесь .

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

Table of Contents
Hide
  1. What is TypeError: only size-1 arrays can be converted to python scalars?
  2. How to fix TypeError: only size-1 arrays can be converted to python scalars?
    1. Solution 1 – Vectorize the function using np.vectorize
    2. Solution 2 – Cast the array using .astype() method
  3. Conclusion

We get this error generally while working with NumPy and Matplotlib. If you have a function that accepts a single value, but if you pass an array instead, you will encounter TypeError: only size-1 arrays can be converted to python scalars.

In this tutorial, we will learn what is TypeError: only size-1 arrays can be converted to python scalars and how to resolve this error with examples.

Python generally has a handful of scalar values such as int, float, bool, etc. However, in NumPy, there are 24 new fundamental Python types to describe different types of scalars. 

Due to this nature, while working with NumPy, you should ensure to pass a correct type, else Python will raise a TypeError.

Let us take a simple example to reproduce this error. 

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value


def my_function(x):
    return int(x)

data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, my_function(data))
plt.show()

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodemain.py", line 14, in <module>
    plt.plot(data, my_function(data))
  File "c:PersonalIJSCodemain.py", line 9, in my_function
    return int(x)
TypeError: only size-1 arrays can be converted to Python scalars

In the above example, we have an int function that accepts only single values. However, we are passing an array to the np.int() or int() method, which will not work and results in TypeError.

How to fix TypeError: only size-1 arrays can be converted to python scalars?

There are two different ways to resolve this error. Let us take a look at both solutions with examples.

Solution 1 – Vectorize the function using np.vectorize

If you are working with a simple array and then vectorizing, this would be the best way to resolve the issue.

The int() accepts a single parameter and not an array according to its signature. We can use np.vectorize() function, which takes a nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.

Behind the scenes, it’s a for loop that iterates over each array element and returns a single NumPy array as output.

Let us modify our code to use the np.vectorize() method and run the program.

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value

def my_function(x):
    return int(x)


# vectorize the function
f = np.vectorize(my_function)

data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, f(data))
plt.show()

Output

We can see that error is gone, the vectorize() function will loop through the array and returns a single array that is accepted by the int() function.

Image 9

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

Solution 2 – Cast the array using .astype() method

The np.vectorize() method is inefficient over the larger arrays as it loops through each element.

The better way to resolve this issue is to cast the array into a specific type (int in this case) using astype() method.

# import numpy and matplotlib
import numpy as np
import matplotlib.pyplot as plt

# function which accepts scalar value


def my_function(x):
    # csat the array into integer
    return x.astype(int)


data = np.arange(1, 22, 0.4)

# passing an array to function
plt.plot(data, my_function(data))
plt.show()

Output

Only Size-1 Arrays Can Be Converted To Python Scalars

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

Conclusion

We get TypeError: only size-1 arrays can be converted to python scalars if we pass an array to the method that accepts only scalar values.

The issue can be resolved by using np.vectorize() function a nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.

Another way to resolve the error is to use the astype() method to cast the array into an integer type.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

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

In Python, you can use the numpy library when working with arrays and certain math concepts like matrices and linear algebra.

But like every other aspect of learning and working with a programming language, errors are unavoidable.

In this article, you’ll learn how to fix the «TypeError: only size-1 arrays can be converted to Python scalars» error which mostly occurs when using the numpy library.

What Causes the TypeError: only size-1 arrays can be converted to Python scalars Error in Python?

The «TypeError: only size-1 arrays can be converted to Python scalars» error is raised when we pass in an array to a method that accepts only one parameter.

Here’s an example:

import numpy as np

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

print(x)

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

The code above throws the «TypeError: only size-1 arrays can be converted to Python scalars» error because we passed the y array to the NumPy int() method. The method can only accept one parameter.

In the next section, you’ll see some solutions for this error.

There are two general solutions for fixing the «TypeError: only size-1 arrays can be converted to Python scalars» error.

Solution #1 – Using the np.vectorize() Function

The np.vectorize() function can accept a sequence/an array as its parameter. When printed out, it returns an array.

Here’s an example:

import numpy as np

vector = np.vectorize(np.int_)
y = np.array([2, 4, 6, 8])
x = vector(y)

print(x)
# [2, 4, 6, 8]

In the example above, we created a vector variable which will «vectorize» any parameter passed to it: np.vectorize(np.int_).

We then created an array and stored it in the y variable: np.array([2, 4, 6, 8]).

Using the vector variable we created initially, we passed the y array as a parameter: x = vector(y).

When printed out, we got the array — [2, 4, 6, 8].

Solution #2 – Using the map() Function

The map() function accepts two parameter in this case — the NumPy method and the array.

import numpy as np

y = np.array([2, 4, 6, 8])
x = np.array(list(map(np.int_, y)))

print(x)
# [2, 4, 6, 8]

In the example above, we nested the map() function in a list() method so that we get the array retuned as a list and not a map object.

Solution #3 – Using the astype() Method

We can use the astype() method to convert a NumPy array to integers. This will prevent the «TypeError: only size-1 arrays can be converted to Python scalars» error from being raised.

Here’s how:

import numpy as np

vector = np.vectorize(np.int_)
y = np.array([2, 4, 6, 8])
x = y.astype(int)

print(x)
# [2 4 6 8]

Summary

In this article, we talked about the «TypeError: only size-1 arrays can be converted to Python scalars» error in Python.

It is raised when we pass an array as a parameter to a numpy method that accepts only one parameter.

To fix the error, we used different methods like the np.vectorize() function, map() function, and astype() method.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Возможно, вам также будет интересно:

  • Online проверка текста на ошибки
  • Online plugin citrix ошибка
  • Onkyo ng lr ошибка
  • Onenotem exe системная ошибка
  • Onenotem exe ошибка при запуске приложения 0xc0000142

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии