Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy convert scalars to arrays

Tags:

python

numpy

I am evaluating arbitrary expressions in terms of an x array, such as 3*x**2 + 4. This normally results in an array with x's shape. However if the expression is just a constant, it returns a scalar. What is the best way to ensure it has x's shape without explicitly checking the shape? Multiplying by numpy.ones(x.shape) works, but I think that uses unnecessary computations.

Edit: To be clear, I don't just want it to be an array with size one, I want it to be the same shape and size as X. I'm evaluating a string using NumExpr which can contain an arbitrary function of x:

x = numpy.linspace(min, max, num)
y = numexpr.evaluate(expr, {'x': x}, {})

I want to get an array of y-values that could be plotted against x through matplotlib. Currently I am doing this, which works fine:

y = numpy.ones(x.size) * y

But I'm worried that this is wasteful for large sizes. Is there a better way?

like image 931
Ryan McCampbell Avatar asked May 21 '15 22:05

Ryan McCampbell


People also ask

How do you convert an object to an array in Python?

Using numpy.asarray() , and true (by default) in the case of np. array() . This means that np. array() will make a copy of the object (by default) and convert that to an array, while np.

What is NP Asarray?

asarray() function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays. Syntax : numpy.asarray(arr, dtype=None, order=None)

What is a NumPy scalar?

In NumPy, a scalar is any object that you put in an array. It's similar to the concept in linear algebra, an element of a field which is used to define a vector space. NumPy ensures all scalars in an array have same types. It's impossible one scalar having type int32, the other scalars having type int64.


1 Answers

See atleast_1d:

Convert inputs to arrays with at least one dimension.

>>> import numpy as np
>>> x = 42  # x is a scalar
>>> np.atleast_1d(x)
array([42])

>>> x_is_array = np.array(42)  # A zero dim array
>>> np.atleast_1d(x_is_array)
array([42])

>>> x_is_another_array = np.array([42])  # A 1d array
>>> np.atleast_1d(x_is_another_array)
array([42])

>>> np.atleast_1d(np.ones((3, 3)))  # Any other numpy array
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
like image 171
Constructor Avatar answered Oct 23 '22 00:10

Constructor