在 NumPy 中,将数组数据作为包含数组中原始字节的字符串返回
要在 NumPy 中将数组数据作为包含原始字节的字符串返回,请使用 **ma.MaskedArray.tobytes()** 方法。在字符串转换之前,数组将填充填充值。
fill_value 是用于填充掩码值的数值。默认为 None,在这种情况下,将使用 *MaskedArray.fill_value*。
order 参数是副本中数据项的顺序。默认为 'C'。
'C' - C 顺序(行优先)。
'F' - Fortran 顺序(列优先)。
'A' - 任意,数组的当前顺序
None - 与 'A' 相同。
步骤
首先,导入所需的库:
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建一个包含整数元素的数组:
arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)获取数组的维度:
print("Array Dimensions...
",arr.ndim)创建一个掩码数组,并将其中一些标记为无效:
maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 0]])
print("
Our Masked Array
", maskArr)
print("
Our Masked Array type...
", maskArr.dtype)获取掩码数组的维度:
print("
Our Masked Array Dimensions...
",maskArr.ndim)获取掩码数组的形状:
print("
Our Masked Array Shape...
",maskArr.shape)获取掩码数组的元素个数:
print("
Elements in the Masked Array...
",maskArr.size)
要在 NumPy 中将数组数据作为包含数组中原始字节的字符串返回,请使用 ma.MaskedArray.tobytes() 方法:
print("
Result...
",maskArr.tobytes())示例
# 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...
", arr)
print("
Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Array Dimensions...
",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("
Our Masked Array
", maskArr)
print("
Our Masked Array type...
", maskArr.dtype)
# Get the dimensions of the Masked Array
print("
Our Masked Array Dimensions...
",maskArr.ndim)
# Get the shape of the Masked Array
print("
Our Masked Array Shape...
",maskArr.shape)
# Get the number of elements of the Masked Array
print("
Elements in the Masked Array...
",maskArr.size)
# To return the array data as a string containing the raw bytes in the array, use the ma.MaskedArray.tobytes() method in Numpy
print("
Result...
",maskArr.tobytes())输出
Array... [[49 85 45] [67 33 59]] Array type... int64 Array Dimensions... 2 Our Masked Array [[49 85 --] [67 -- 59]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (2, 3) Elements in the Masked Array... 6 Result... 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'
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP