The asarray()
method converts all array_like objects into an array.
import numpy as np
# create array-like objects
list1 = [1, 2, 3, 4, 5]
tuple1 = (1, 2, 3, 4, 5)
# convert them to arrays
array1 = np.asarray(list1)
array2 = np.asarray(tuple1)
print(array1)
print(array2)
'''
Output:
[1 2 3 4 5]
[1 2 3 4 5]
'''
asarray() Syntax
The syntax of asarray()
is:
numpy.asarray(a, dtype = None, order = None, like = None)
asarray() Argument
The asarray()
method takes the following arguments:
a
- anyarray_like
input objectdtype
(optional)- type of output array(dtype
)order
(optional)- specifies the order in which the array elements are placedlike
(optional)- reference object to allow the creation of non-NumPy arrays
asarray() Return Value
The asarray()
method returns an array representation of a
.
Example 1: Convert to an Array Using asarray
import numpy as np
# create array-like objects
list1 = [1, 2, 3, 4, 5]
# convert them to arrays
array1 = np.asarray(list1)
array2 = np.asarray(list1, dtype = str)
print(array1)
print(array2)
Output
[1 2 3 4 5] ['1' '2' '3' '4' '5']
Note: Using the dtype
argument specifies the data type of the resultant array.
Key Difference Between np.array() and np.asarray()
Both np.array()
and np.asarray()
are NumPy functions used to generate arrays from array_like objects but they have some differences in their behavior.
The array()
method creates a copy of an existing object whereas asarray()
creates a new object only when needed.
Let us see an example.
import numpy as np
# create an array
array1 = np.arange(5)
# use np.array() on existing array
array2 = np.array(array1)
print('Using array():', array1 is array2) # makes a copy
# use np.asarray() on existing array
array3 = np.asarray(array1)
print('Using asarray():', array1 is array3) # doesn't make a copy
Output
Using array(): False Using asarray(): True