In Numpy, its library provides us various ways to create a NumPy Array from existing data. They are as follows:
numpy.asarray:
It is used to create array by using existing data which is in form of lists, or tuples.It is somehow similar to numpy.array but it has fewer parameters as compared to numpy.array
. It is used to convert python sequence into the numpay array.
Syntax:
numpy.asarray(sequence, dtype , order)
Parameters:
- sequence:It is used to represent the input data which is python sequence which will be used to for converting into python array.
- dtype: It is used to describe the data type of each element in ndarray.
- order: It can either be set to C or F. Its default is C.
Example:
import numpy as np
x = [1,2,3,4,5,6,7]
y = ('a','b','c','d','e','f','g','h')
a = np.asarray(x)
b = np.asarray(y)
print(a)
print(b)
print(type(a))
print(type(b))
Output:
[1 2 3 4 5 6 7] ['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h'] <class 'numpy.ndarray'> <class 'numpy.ndarray'>
numpy.frombuffer:
This function returns an ndarray by using the specified buffer. It is used to interpret a buffer as 1-D array.
Syntax:
numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)
Parameters:
buffer: It represent an object that exposes a buffer interface.
type: It represent the data type of ndarray.
count: It is used to represent the length of ndarray.
offset: It is the starting position from where to read from. Its default value is 0.
Example:
import numpy as np
x= b'ProgramsBuzz'
a = np.frombuffer(x, dtype = "S1")
print(a)
print(type(a))
Output:
[b'P' b'r' b'o' b'g' b'r' b'a' b'm' b's' b'B' b'u' b'z' b'z'] <class 'numpy.ndarray'>
numpy.fromiter:
This function is used to create a ndarray by using an iterable object. It returns a on1-D ndarray.
Syntax:
numpy.fromiter(iterable, dtype, count = -1)
Parameters:
- iterable: It is used to an iterable object.
- type: It is used to describe data type of ndarray.
- count: It is used to represents the number of items to read from the buffer in the array.
Example:
import numpy as np
x=(x**2 for x in range(6))
a=np.fromiter(x,dtype=float)
print(a)
Output: [ 0. 1. 4. 9. 16. 25.]