Skip to main content

NumPy: Create an Array from Existing data

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:

  1. sequence:It is used to represent the input data which is python sequence which will be used to for converting into python array.
  2. dtype: It is used to describe the data type of each element in ndarray.
  3. 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:

  1. buffer: It represent an object that exposes a buffer interface.

  2. type: It represent the data type of ndarray.

  3. count: It is used to represent the length of ndarray.

  4. 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:

  1. iterable: It is used to an iterable object.
  2. type: It is used to describe data type of ndarray.
  3. 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.]

Submitted by devanshi.srivastava on August 5, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.