w3resource

NumPy: Convert the raw data in an array to a binary string and then create an array

NumPy: Array Object Exercise-98 with Solution

Write a NumPy program to convert the raw data in an array to a binary string and then create an array.

Sample Solution:

Python Code:

import numpy as np
x = np.array([10, 20, 30], float)
print("Original array:")
print(x)
s = x.tostring()
print("Binary string array:")
print(s)
print("Array using fromstring():")
y = np.fromstring(s)
print(y)

Sample Output:

Original array:                                                                        
[ 10.  20.  30.]                                                                       
Binary string array:                                                                   
b'\x00\x00\x00\x00\x00\[email protected]\x00\x00\x00\x00\x00\[email protected]\x00\x00\x00\x00\x00\x00>@'      
Array using fromstring():                                                              
[ 10.  20.  30.]

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to print all the values of an array.
Next: Write a NumPy program to sum and compute the product of a numpy array elements.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]