
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create 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)]