# Return the array data as a string containing the raw bytes in the array in Numpy

NumpyServer Side ProgrammingProgramming

To return the array data as a string containing the raw bytes in the array, use the ma.MaskedArray.tobytes() method in Numpy. The array is filled with a fill value before the string conversion.

The fill_value is the value used to fill in the masked values. Default is None, in which case MaskedArray.fill_value is used.

The order parameter is the Order of the data item in the copy. Default is ‘C’.

• ‘C’ - C order (row major).

• ‘F’ - Fortran order (column major).

• ‘A’ - Any, current order of array

• None - Same as ‘A’.

## Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array with int elements using the numpy.array() method −

arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

Get the dimensions of the Array −

print("Array Dimensions...\n",arr.ndim)

Create a masked array and mask some of them as invalid −

maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 0]])
print("\nOur Masked Array type...\n", maskArr.dtype)

Get the dimensions of the Masked Array −

print("\nOur Masked Array Dimensions...\n",maskArr.ndim)

Get the shape of the Masked Array −

print("\nOur Masked Array Shape...\n",maskArr.shape)

Get the number of elements of the Masked Array −

print("\nElements in the Masked Array...\n",maskArr.size)


Return the array data as a string containing the raw bytes in the array, use the ma.MaskedArray.tobytes() method in Numpy −

print("\nResult...\n",maskArr.tobytes())

## Example

# Python ma.MaskedArray - Return the array data as a string containing the raw bytes in the array

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Create a masked array and mask some of them as invalid

# Get the dimensions of the Masked Array

# Get the shape of the Masked Array

# Get the number of elements of the Masked Array

# To return the array data as a string containing the raw bytes in the array, use the ma.MaskedArray.tobytes() method in Numpy
print("\nResult...\n",maskArr.tobytes())

## Output

Array...
[[49 85 45]
[67 33 59]]

Array type...
int64

Array Dimensions...
2

[[49 85 --]
[67 -- 59]]

int64

b'1\x00\x00\x00\x00\x00\x00\x00U\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00C\x00\x00\x00\x00\x00\x00\x00?B\x0f\x00\x00\x00\x00\x00;\x00\x00\x00\x00\x00\x00\x00'