NumPy Tutorial NumPy Statistics NumPy References

NumPy - frombuffer() function



The NumPy frombuffer() function is used to interpret a buffer as a 1-dimensional array. The syntax for using this function is given below:

Syntax

numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)

Parameters

buffer Required. Specify an object that exposes the buffer interface.
dtype Optional. Specify the desired data type. Default is float.
count Optional. Specify the number of items to read. Default is -1 which means all data in the buffer.
offset Optional. Start reading the buffer from this offset (in bytes). Default is 0.

Return Value

Returns array version of the buffer.

Example:

In the example below, the frombuffer() function is used to create a numpy array from a buffer.

import numpy as np

x = b"Hello World"

#creating 1-D numpy array from buffer
Arr1 = np.frombuffer(x, dtype='S1')
print("Arr1 is:", Arr1)

#using count parameter
Arr2 = np.frombuffer(x, dtype='S1', count=5)
print("\nArr2 is:", Arr2)

#using count and offset parameter
Arr3 = np.frombuffer(x, dtype='S1', count=5, offset=6)
print("\nArr3 is:", Arr3)

The output of the above code will be:

Arr1 is: [b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

Arr2 is: [b'H' b'e' b'l' b'l' b'o']

Arr3 is: [b'W' b'o' b'r' b'l' b'd']

❮ NumPy - Functions