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 raw array data to a binary string and create an array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing floating-point values
x = np.array([10, 20, 30], float)

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'x' with its elements
print(x)

# Converting the array 'x' to a binary string using the 'tostring()' method
s = x.tostring()

# Printing a message indicating the display of the binary string array
print("Binary string array:")

# Printing the binary string representation of array 'x'
print(s)

# Printing a message indicating the array creation using 'fromstring()'
print("Array using fromstring():")

# Creating a new NumPy array 'y' by converting the binary string 's' back to an array using 'fromstring()'
# Note: This method may be deprecated in future versions of NumPy.
y = np.fromstring(s)

# Printing the array 'y' obtained from the binary string
print(y) 

Sample Output:

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

Explanation:

In the above code –

x = np.array([10, 20, 30], float): Create a NumPy array 'x' with the elements 10, 20, and 30 of float data type.

s = x.tostring(): This line converts the NumPy array 'x' to a binary string 's' using the 'tostring()' method. Note that since NumPy 1.9, the preferred method is 'tobytes()' instead of 'tostring()'.

y = np.fromstring(s): Create a new NumPy array 'y' from the binary string 's' using the 'np.fromstring()' function. The new array 'y' will have the same elements as the original array 'x'.

Python-Numpy Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-98.php