← Back to NumPy Course | Chapter 11: File I/O | Lesson 5 of 5

np.frombuffer()

frombuffer builds an array straight from raw bytes in memory, without copying.

In this page:

  1. np.frombuffer()
Syntax
python
arr = np.frombuffer(buffer, dtype=dtype)

np.frombuffer()

np.frombuffer interprets a bytes-like object as a 1-D array of the dtype you name. It shares memory with the source buffer, so it is fast. The buffer must be large enough for whole elements. Results from immutable bytes are read-only.

Note: Make a writable copy with .copy() if you need to modify the data.

Example: np.frombuffer()

python
import numpy as np

raw = b"\x01\x02\x03\x04"
a = np.frombuffer(raw, dtype=np.uint8)
print(a)
print(a.flags.writeable)
b = np.arange(3, dtype=np.int16).tobytes()
print(b)
print(np.frombuffer(b, dtype=np.int16))

# Output:
# [1 2 3 4]
# False
# b'\x00\x00\x01\x00\x02\x00'
# [0 1 2]
Related Topics
Common Mistakes
  1. Forgetting to specify dtype
  2. Passing a buffer whose length is not a multiple of itemsize
  3. Trying to modify a read-only array
Chapter Summary
  • frombuffer wraps raw bytes
  • It does not copy data
  • dtype defines the interpretation
  • Bytes input gives read-only arrays
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.