Difference between frombuffer() and fromstring() in Python NumPy

In this tutorial, we will learn about the difference between frombuffer() and fromstring() in Python NumPy with the help of examples. By Pranit Sharma Last updated : May 05, 2023

When frombuffer() is used?

If we were working with something that exposed the buffer interface, then we probably want to use frombuffer(). Python 2.x strings and Python 3.x bytes expose the buffer interface, but we will get a read-only array, as Python strings are immutable.

When fromstring() is used?

If not then, we use fromstring() to create a NumPy array from a string. Buffer is a way for C-level libraries to expose a block of memory for use in Python. It is basically a Python interface for managed access to raw memory.

Difference between frombuffer() and fromstring()

The main difference between frombuffer() and fromstring() is that fromstring() creates a copy of the string in memory, whereas, frombuffer() uses the memory buffer of the string directly and will not use any additional memory.

Let us understand with the help of an example,

Python program to demonstrate the difference between frombuffer() and fromstring() methods

# Import numpy
import numpy as np

# Creating a string
s = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

# Creating array using fromstring
arr = np.fromstring(s)

# Display array
print("Array with fromstring:\n",arr,"\n")

# Creating array using frombuffer
arr = np.fromstring(s)

# Display array
print("Array with frombuffer:\n",arr,"\n")

Output

Difference between frombuffer() and fromstring() | Output

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.