w3resource

NumPy: numpy.asarray() function

numpy.asarray() function

The numpy.asarray() function is used to convert n given input to an array.

Syntax:

numpy.asarray(a, dtype=None, order=None)
NumPy manipulation: asarray() function

Parameters:

Name Description Required /
Optional
a Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. Required
dtype By default, the data-type is inferred from the input data. Optional
order Whether to use row-major (C-style) or column-major (Fortranstyle) memory representation. Defaults to 'C'. Optional

Return value:

out [ndarray] Array interpretation of a. No copy is performed if the input is already an ndarray with matching dtype and order. If a is a subclass of ndarray, a base class ndarray is returned.

Raises: ValueError - If axis is not None, and an axis being squeezed is not of length 1

Example-1: numpy.asarray()

>>> import numpy as np
>>> a = [3, 5]
>>> np.array(a)
array([3, 5])
>>> a = np.asarray([3, 5])
>>> np.asarray(a) is a
True

Pictorial Presentation:

NumPy manipulation: asarray() function

Example-2: numpy.asarray()

>>> import numpy as np
>>> x = np.array([3, 5], dtype=np.float32)
>>> np.asarray(x, dtype=np.float32) is x
True
>>> np.asarray(x, dtype=np.float64) is a
False
>>> issubclass(np.recarray, np.ndarray)
True
>>> x = np.array([(2.0, 3), (4.0, 5)], dtype='f4,i4').view(np.recarray)
>>> np.asarray(x) is a
False
>>> np.asanyarray(x) is x
True

Python - NumPy Code Editor:

Previous: squeeze()
Next: asanyarray()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/numpy/manipulation/asarray.php