交换NumPy中掩码数组数据的字节


要交换数组元素的字节,请使用NumPy中的**ma.MaskedArray.byteswap()**方法。通过返回一个字节交换后的数组(可选地就地交换)来在低位序和高位序数据表示之间切换。字节字符串数组不会被交换。复数的实部和虚部分别被交换。它返回字节交换后的数组。如果inplace为True,则这是一个指向自身的视图。

numpy.ma.MaskedArray是ndarray的子类,旨在处理具有缺失数据的数值数组。MaskedArray的实例可以被认为是几个元素的组合:

步骤

首先,导入所需的库:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法创建一个包含整数元素的数组:

arr = np.array([[35, 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中的numpy.byteswap()方法:

print("
After Swap...
",maskArr.byteswap())

示例

# Python ma.MaskedArray - Swap the bytes of the masked array data

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[35, 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 swap the bytes of the array elements, use the byteswap() method in Numpy print("
After Swap...
",maskArr.byteswap())

输出

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

Array type...
int64

Array Dimensions...
2

Our Masked Array
[[35 85 --]
[67 -- 59]]

Our Masked Array type...
int32

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(2, 3)

Elements in the Masked Array...
6

After Swap...
[[2522015791327477760 6124895493223874560 --]  
[4827858800541171712 -- 4251398048237748224]]

更新于:2022年2月2日

205 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告