numpy
  1. numpy-numpyfrombuffer

numpy.frombuffer() - ( Creating Arrays with NumPy )

Heading h2

Syntax

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

Example

import numpy as np

string = b'hello world'
arr = np.frombuffer(string, dtype='S1')
print(arr)

Output

array([b'h', b'e', b'l', b'l', b'o', b' ', b'w', b'o', b'r', b'l', b'd'],
      dtype='|S1')

Explanation

The numpy.frombuffer() function creates a new 1-dimensional array from an object that supports the Python buffer protocol. It is useful when you want to create an array directly from the raw binary buffer of an object such as a string or a byte array.

The function takes four arguments, buffer, dtype, count, and offset. buffer is the object containing the binary data, dtype is the data type of the resulting array, count is the number of items to read from the buffer, and offset is the number of bytes to skip before starting to read the data.

Use

The numpy.frombuffer() function is used to create a NumPy array from the raw binary buffer of an object such as a string or a byte array. It can be useful when you're working with binary data and want to create a NumPy array to manipulate the data.

Important Points

  • The numpy.frombuffer() function is used to create a new 1-dimensional array from an object that supports the Python buffer protocol.
  • The function takes four arguments, buffer, dtype, count, and offset.
  • buffer is the object containing the binary data, dtype is the data type of the resulting array, count is the number of items to read from the buffer, and offset is the number of bytes to skip before starting to read the data.
  • The numpy.frombuffer() function is useful when you're working with binary data and want to create a NumPy array to manipulate the data.

Summary

In conclusion, the numpy.frombuffer() function is a great way to create a new NumPy array from the raw binary buffer of an object such as a string or a byte array. It can be useful when you're working with binary data and want to perform operations on it using NumPy. Just keep in mind that you need to specify the correct data type and byte order for the resulting array.

Published on: