NumPy frombuffer() function

The numpy.frombuffer() function of the Numpy library is used to create an array by using the specified buffer.

This function interprets a buffer as a 1-dimensional array.

Syntax of frombuffer():

Given below is the required syntax that is used for numpy.frombuffer() function:

numpy.frombuffer(buffer, dtype, count, offset) 

Parameters:

Let us discuss the parameters of the above constructor:

  • buffer
    This parameter is used to represent an object that exposes a buffer interface.
  • dtype
    This parameter is used to represent the data type of the returned data type array. The default value of this parameter is 0.
  • count
    This parameter represents the length of the returned ndarray. The default value of this parameter is -1.
  • offset
    This parameter indicates the starting position to read from. The default value of this parameter is 0.

Let us now discuss some examples using frombuffer() function.

Basic Example:

Below we have the code snippet in order to understand the working of this function:

import numpy as np  

input = b'Welcome to ShishirKant!!!It is a best place for you to learn coding online..'  
print("The type of input is:") 
print(type(input))

a = np.frombuffer(input, dtype = "S1")  
print("The Output is:") 
print(a)

print("Type of Output is:")
print(type(a))  

Output:

The type of input is:
<class 'bytes'>
The Output is:
[b'W' b'e' b'l' b'c' b'o' b'm' b'e' b' ' b't' b'o' b' ' b'S' b'h' b'i'
b's' b'h' b'i' b'r' b'K' b'a' b'g' b'n' b't' b'!' b'!' b'!' b'I' b't'
b' ' b'i' b's' b' ' b'a' b' ' b'b' b'e' b's' b't' b' ' b'p' b'l' b'a'
b'c' b'e' b' ' b'f' b'o' b'r' b' ' b'y' b'o' b'u' b' ' b't' b'o' b' '
b'l' b'e' b'a' b'r' b'n' b' ' b'c' b'o' b'd' b'i' b'n' b'g' b' ' b'o'
b'n' b'l' b'i' b'n' b'e' b'.' b'.']
Type of Output is:
<class 'numpy.ndarray'>
Follow Us On