Create a record array from binary data in Numpy


To create a record array from binary data, use the numpy.core.records.fromstring() method in Python Numpy. We have used the tobytes() method for binary data.

The first parameter is the datastring i.e. the buffer of binary data. The function returns the record array view into the data in datastring. This will be readonly if datastring is readonly. The offset parameter is the position in the buffer to start reading from. The formats, names, titles, aligned, byteorder parameters, if dtype is None, these arguments are passed to numpy.format_parser to construct a dtype.

Steps

At first, import the required library −

import numpy as np

Set the array type −

my_type = [('Team', (np.str_, 10)), ('Points', np.float64),('Rank', np.int32)]

Display the array −

print("Record Array types...
",my_type)

Create an array using the numpy.array() method −

arr = np.array([('AUS', 115, 5), ('NZ', 125, 3),('IND', 150, 1)], dtype=my_type)

Display the array −

print("
Array...
",arr)

To create a record array from binary data, use the numpy.core.records.fromstring() method. We have used the tobytes() method for binary data −

rec = np.core.records.fromstring(arr.tobytes(), dtype=my_type)
print("
Record Array...
",rec)

Example

import numpy as np

# Set the array type
my_type = [('Team', (np.str_, 10)), ('Points', np.float64),('Rank', np.int32)]

# Display the type
print("Record Array types...
",my_type) # Create an array using the numpy.array() method arr = np.array([('AUS', 115, 5), ('NZ', 125, 3),('IND', 150, 1)], dtype=my_type) # Display the array print("
Array...
",arr) # To create a record array from binary data, use the numpy.core.records.fromstring() method in Python Numpy # We have used the tobytes() method for binary data rec = np.core.records.fromstring(arr.tobytes(), dtype=my_type) print("
Record Array...
",rec)

Output

Record Array types...
[('Team', (<class 'numpy.str_'>, 10)), ('Points', <class 'numpy.float64'>), ('Rank', <class 'numpy.int32'>)]

Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)]

Record Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)]

Updated on: 10-Feb-2022

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements