将掩码数组数据作为包含数组中原始字节的字符串返回,并在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)

将数组数据作为包含数组中原始字节的字符串返回,使用ma.MaskedArray.tobytes()。"fill_value"参数是用于填充掩码值的数值。默认为None,在这种情况下,将使用MaskedArray.fill_value -

print("
Result...
",maskArr.tobytes(fill_value = 1111))

示例

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

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 # The "fill_value" parameter ios the value used to fill in the masked values. # Default is None, in which case MaskedArray.fill_value is used. print("
Result...
",maskArr.tobytes(fill_value = 1111))

输出

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\x00W\x04\x00\x00\x00\x00\x00\x00C\x00\x00\x00\x00\x00\x00\x00W\x04\x00\x00\x00\x00\x00\x00;\x00\x00\x00\x00\x00\x00\x00'

更新于: 2022年2月2日

283 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.