Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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("\nArray...
",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("\nRecord 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("\nArray...
",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("\nRecord Array...
",rec)
Output
Record Array types...
[('Team', (, 10)), ('Points', ), ('Rank', )]
Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)]
Record Array...
[('AUS', 115., 5) ('NZ', 125., 3) ('IND', 150., 1)] 