×

NumPy Array Creation from Existing Data

The NumPy library supports ndarray creation using existing data as well. The following are the list of functions that creates ndarray from an existing data source:

  • asarray() function
  • frombuffer() function
  • fromiter() function

asarray() function

The asarray() function is specifically used to convert any Python sequences(list, tuples) into ndarray. The asarray() function of NumPy is a similar to the NumPy’s array() function. The difference is that the asarray() function has fewer parameters than the array() function.

Syntax:

asarray(a, dtype=None, order=None, *, like=None)

The following are parameters of asarray() function:

  • a: This parameter is data sequence in any form that can be converted to array(all combinations of lists, tuples).
  • dtype: This parameter sets the data type of elements in ndarray.

The a parameter is mandatory and dtype, order, and like parameters are optional in asarray() function.

asarray() to create ndarray from list:

We import the NumPy package using import statement. Now we create a Python list of integers name plst. We pass plst as a parameter in asarray() function and store the resultant ndarray as np_arr.

import numpy as np
plst=[1, 2, 3, 4] #Python List
np_arr = np.asarray(plst)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([1, 2, 3, 4])

asarray() to create ndarray from list of lists, dtype to int:

 plol=[[1.5, 2.9], [3.2, 4.7]] #Python List of Lists
np_arr = np.asarray(plol, dtype=int)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([[1, 2],
          [3, 4]])

asarray() to create ndarray from the tuple, dtype to float:

ptup=(6, 2, 8, 4) #Python Tuple
np_arr = np.asarray(ptup, dtype=float)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([6., 2., 8., 4.])

asarray() to create ndarray from a tuple of tuples, dtype to bool:

ptot=((1, 2), (6, 7)) #Python Tuple of Tuples
np_arr = np.asarray(ptot, dtype=bool)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([[ True,  True],
          [ True,  True]])

asarray() to create ndarray from list of tuples, dtype to str:

plot=[(3, 4, 5), (6, 7, 8)] #Python List of Tuples
#converting plot to ndarray
np_arr = np.asarray(plot, dtype=str)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([['3', '4', '5'],
         ['6', '7', '8']], dtype='< U1')

asarray() to create ndarray from a tuple of lists, dtype to complex:

ptol=([1, 6], [2, 19]) #Python Tuple of lists
np_arr = np.asarray(ptol, dtype=complex)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([[ 1.+0.j,  6.+0.j],
         [ 2.+0.j, 19.+0.j]])

frombuffer() function

The frombuffer() function in NumPy is used for creating ndarray from buffers. A buffer in python is an object’s byte-oriented data stream or sequence. The frombuffer() function interprets a buffer as a 1-dimensional array.

Syntax:

frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)

Following are the arguments of frombuffer() function:

  • buffer: This parameter is data object that exposes buffer interface(byte-oriented).
  • dtype: This parameter is same as the asarray() function with the default set to float.
  • count: This parameter is the number of input elements to read(default is set -1 means it will read all data in the buffer).
  • offset: This parameter is the start position to read the buffer(default is set 0).

The buffer is a mandatory parameter and dtype, count, offset, and like are optional parameters in frombuffer() function.

frombuffer() to create ndarray from Byte-String:

We create a byte-string by putting a b(byte) in front of the string and store it as byte_str. Then we pass byte_str as a buffer in frombuffer() function and set dtype to ‘S1’(byte string, 1 byte).

byte_str = b"Welcome to NumPy"  #byte string
np_arr = np.frombuffer(byte_str, dtype='S1')
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([b'W', b'e', b'l', b'c', b'o', b'm', b'e', b' ', b't', b'o', b' ',
       b'N', b'u', b'm', b'P', b'y'], dtype='|S1')

frombuffer() offset parameter:

byte_str = b'Hello World' #byte string
np_arr = np.frombuffer(byte_str, dtype='S1', offset = 2)
np_arr  #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([b'l', b'l', b'o', b' ', b'W', b'o', b'r', b'l', b'd'], dtype='|S1')

frombuffer() count parameter:

byte_str = b'How Are You' #byte string
np_arr = np.frombuffer(byte_str, dtype='S1', count = 7)
np_arr  #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([b'H', b'o', b'w', b' ', b'A', b'r', b'e'], dtype='|S1')

fromiter() function

The fromiter() function in NumPy is used for creating ndarray from any iterable object. An iterable object in python is an object that provides data for an array in iteration. The fromiter() function returns a 1-dimensional ndarray.

Syntax:

fromiter(iter, dtype, count=-1, *, like=None)

Following are the arguments of frombuffer() function:

  • iter: This parameter is any iterable object as input.
  • dtype: This parameter is same as the asarray() function.
  • count: This parameter is same as the frombuffer() function.

The iter and dtype are mandatory parameters, count, and like are the optional parameters in fromiter() function.

fromiter() to create ndarray from range():

The range() function is a Python built-in function used to get iteration(sequence) of numbers. The range() function returns an object that produces a sequence of integers.

A quick example is shown here:

#range() function
print(range(9)) #iterable object
print(list(range(9))) #list containing values of iterable object
#Output:
range(0, 9)
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Creating a range object range_itr using range() function and passing range_itr as iter in fromiter() function and set dtype to complex.

range_itr = range(5) #range object (iterable object)
np_arr = np.fromiter(range_itr, dtype=complex)
np_arr #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j])

fromiter() to create ndarrray from Python list:

py_lst = [1, 2, 3, 4, 5, 6, 7] #Python list
#list(iterable object) to ndarray
np_arr = np.fromiter(py_lst, dtype= float, count=3)
np_arr  #other than Jupyter Notebook users, use print(np_arr)
#Output:
array([1., 2., 3.])