Python iter_unpack to NumPy Array: Efficient Binary Data Conversion
To use the 'iter_unpack' function in Python to create a NumPy array, you can follow these steps:
- Import the necessary libraries:
import numpy as np
import struct
- Define the format string to unpack the binary data:
fmt = '<fff'
This format string specifies that the binary data contains three floats in little-endian byte order.
- Read the binary data into a buffer:
with open('data.bin', 'rb') as f:
buf = f.read()
- Use 'iter_unpack' to unpack the binary data into a list of tuples:
data = list(struct.iter_unpack(fmt, buf))
- Convert the list of tuples to a NumPy array:
arr = np.array(data)
The resulting 'arr' array will have shape '(N, 3)', where 'N' is the number of tuples in the binary data file. Each row of the array will contain the three floats from the corresponding tuple in the binary data.
原文地址: https://www.cveoy.top/t/topic/mUXA 著作权归作者所有。请勿转载和采集!