NumPy provides us the way to create an array by using the existing data.
This routine is used to create an array by using the existing data in the form of lists, or tuples. This routine is useful in the scenario where we need to convert a python sequence into the numpy array object.
The syntax to use the asarray() routine is given below.
numpy.asarray(sequence, dtype = None, order = None)
It accepts the following parameters.
import numpy as np l=[1,2,3,4,5,6,7] a = np.asarray(l); print(type(a)) print(a)
Output:
import numpy as np l=(1,2,3,4,5,6,7) a = np.asarray(l); print(type(a)) print(a)
Output:
import numpy as np l=[[1,2,3,4,5,6,7],[8,9]] a = np.asarray(l); print(type(a)) print(a)
Output:
This function is used to create an array by using the specified buffer. The syntax to use this buffer is given below.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
It accepts the following parameters.
import numpy as np l = b'hello world' print(type(l)) a = np.frombuffer(l, dtype = "S1") print(a) print(type(a))
Output:
This routine is used to create a ndarray by using an iterable object. It returns a one-dimensional ndarray object.
The syntax is given below.
numpy.fromiter(iterable, dtype, count = - 1)
It accepts the following parameters.
import numpy as np list = [0,2,4,6] it = iter(list) x = np.fromiter(it, dtype = float) print(x) print(type(x))
Output: