Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

NumPy frombuffer() function

In this tutorial, we will cover the numpy.frombuffer() function of the Numpy library.

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 StudyTonight!!!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))  


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't' b'u'
b'd' b'y' b'T' b'o' b'n' b'i' b'g' b'h' 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'>

Summary

This tutorial covered the numpy.frombuffer() function in the Numpy library which is used to create a Numpy ndarray using a given buffer or bytes.