w3resource

NumPy: Convert a given array into bytes, and load it as array

NumPy: Basic Exercise-38 with Solution

Write a NumPy program to convert a given array into bytes, and load it as array.

Sample Solution :

Python Code :

import numpy as np
import os
a = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(a)
a_bytes = a.tostring()
a2 = np.fromstring(a_bytes, dtype=a.dtype)
print("After loading, content of the text file:")
print(a2)
print(np.array_equal(a, a2))

Sample Output:

Original array:
[1 2 3 4 5 6]
After loading, content of the text file:
[1 2 3 4 5 6]
True                         

Python Code Editor:


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

Previous: Write a NumPy program to save a given array to a text file and load it.
Next: Write a NumPy program to convert a given array into a list and then convert it into a list again.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions

Example:

def tips_merge(*args, fill_value=None):
  max_length = max([len(lst) for lst in args])
  result = []
  for i in range(max_length):
    result.append([
      args[k][i] if i < len(args[k])
	  else fill_value for k in range(len(args))
    ])
  return result
print(tips_merge(['x', 'y'], [1, 2], [True, False])) 
print(tips_merge(['x'], [1, 2], [True, False])) 
print(tips_merge(['x'], [1, 2], [True, False], fill_value = '_')) 

Output:

[['x', 1, True], ['y', 2, False]]
[['x', 1, True], [None, 2, False]]
[['x', 1, True], ['_', 2, False]]