numpy.asarray(a, dtype = None, order = None)
The numpy.asarray function converts a data structure to a NumPy array.
This function is similar to np.array (although with fewer options), the biggest difference being the fact that np.array generates -by default- an independent copy of the structure passed as an argument, whereas numpy.asarray does not.
- a: Structure to be converted into a NumPy array. The function supports a large number of types, including lists, tuples, tuple lists, tupa tuples, list tuples, or NumPy arrays. In the latter case, the result of the function is not an independent copy of the array.
- dtype: Type to assign to the result returned by the function. If not specified, this type is inferred from the input structure.
- order: {"C", "F"} In-memory representation of the array. It can be "C" (C-Style) or "F" (Fortran-Style).
The numpy.asarray function returns a NumPy array.
We can convert a list to a NumPy array with the following code:
a = [2, 5, 1, 4]
np.asarray(a)
array([2, 5, 1, 4])
If not specified, the type of the returned array is inferred from the input structure. In the following example the list to be converted includes numbers and texts, so the returned array is generated with a text type as well:
a = [2, 5, 1, "a"]
np.asarray(a)
array(['2', '5', '1', 'a'], dtype='<U11')
If the structure to be converted is a NumPy array, the result returned by the function is not an independent copy of it:
a = np.array([1, 2])
b = np.asarray(a)
a is b
True
We can convert a structure by specifying the type of the generated array:
a = [2, 5, 1, 4]
np.asarray(a, dtype = str)
array(['2', '5', '1', '4'], dtype='<U1')