How to create an array from existing data in NumPy
The asarray() method in NumPy can be used to create an array from data that already exists in the form of lists or tuples.
Syntax
numpy.asarray(a, dtype=None, order=None, *, like=None)
Parameters
-
a: Input data.acan be in the form of a tuple, a list, a list of tuples, a tuple of tuples, or a tuple of lists. -
dtype: The data type to be applied to each element of the array. This parameter is optional. By default, the data type is inferred froma. -
order: A memory layout that can be set asF,C,K, orA.KandAdepend on the order ofa.Fis a column-major representation, andCis a row-major memory representation.- This parameter is optional. The default value of the parameter is
C.
-
like:likeallows arrays that are not NumPy arrays to be created. This parameter is optional. The default value of the parameter isNone.
Return value
The function returns an array.
Code
1. Create an array from a list
import numpy as np#create numpy arrays from listslist1=[5, 3, 6, 2, 1, 5]list2=[10, 3, 32, 95, 12, 34, 3]#print type of both listsprint("Type of list1: ", type(list1))print("Type of list2: ", type(list2))#create arrays from the listsarray1 = np.asarray(list1)array2 = np.asarray(list2)#print type of both arraysprint("Type of array1: ", type(array1))print("Type of array2: ", type(array2))
2. Create an array from a tuple
import numpy as np#create numpy arrays from tuplestuple1 = (43, 21, 32, 67, 21, 5)tuple2=(8, 6, 1, 0, 2, 1, 5)#print type of both tuplesprint("Type of tuple1: ", type(tuple1))print("Type of tuple2: ", type(tuple2))#create arrays from the tuplesarray1 = np.asarray(tuple1)array2 = np.asarray(tuple2)#print type of both arraysprint("Type of array1: ", type(array1))print("Type of array2: ", type(array2))
3. Create an array from a list of tuples
import numpy as np#create an numpy array from a list of tupleslist1 = [(3, 5),(6, 4, 8)]#print typeprint("Type of list1: ", type(list1))#create array from the list of tuplesarray1 = np.asarray(list1)#print typeprint("Type of array1: ", type(array1))