Python Numpy MaskedArray.reshape()函数
numpy.MaskedArray.reshape()函数用于在不改变数据的情况下给被屏蔽的数组一个新的形状。它返回一个包含相同数据的被屏蔽数组,但有一个新的形状。其结果是对原始数组的一个视图;如果这不可能,则会引发ValueError。
语法: numpy.ma.reshape(shape, order)
参数:
shape: [ int or tuple of ints] 新的形状应该与原来的形状兼容。
order: [‘C’, ‘F’, ‘A’, ‘K’, optional] 默认情况下,使用’C’索引顺序。
-> 使用这个索引顺序读取a的元素。
-> ‘C’意味着以类似C的顺序对元素进行索引,最后一个轴索引变化最快,回到第一个轴索引变化最慢。
-> ‘F’意味着以类似Fortran的索引顺序对元素进行索引,第一个索引变化最快,而最后一个索引变化最慢。
-> ‘K’意味着按照元素在内存中出现的顺序来读取,除了在跨度为负数时将数据反转。
返回 : [ reshaped_array] 数组上的一个新视图。
代码#1:
# Python program explaining
# numpy.MaskedArray.reshape() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([1, 2, 3, -1])
print ("Input array : ", in_arr)
# Now we are creating a masked array.
# by making third entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[1, 0, 1, 0])
print ("Masked array : ", mask_arr)
# applying MaskedArray.reshape methods to make
# it a 2d masked array
out_arr = mask_arr.reshape(2, 2)
print ("Output 2D masked array : ", out_arr)
输出:
Input array : [ 1 2 3 -1]
Masked array : [-- 2 -- -1]
Output 2D masked array : [[-- 2]
[-- -1]]
代码#2:
# Python program explaining
# numpy.MaskedArray.reshape() method
# importing numpy as geek
# and numpy.ma module as ma
import numpy as geek
import numpy.ma as ma
# creating input array
in_arr = geek.array([[[ 2e8, 3e-5]], [[ -45.0, 2e5]]])
print ("Input array : ", in_arr)
# Now we are creating a masked array.
# by making one entry as invalid.
mask_arr = ma.masked_array(in_arr, mask =[[[ 1, 0]], [[ 0, 0]]])
print ("3D Masked array : ", mask_arr)
# applying MaskedArray.reshape methods to make
# it a 2d masked array
out_arr = mask_arr.reshape(1, 4)
print ("Output 2D masked array : ", out_arr)
print()
# applying MaskedArray.reshape methods to make
# it a 1d masked array
out_arr = mask_arr.reshape(4, )
print ("Output 1D masked array : ", out_arr)
输出:
Input array : [[[ 2.0e+08 3.0e-05]]
[[-4.5e+01 2.0e+05]]]
3D Masked array : [[[-- 3e-05]]
[[-45.0 200000.0]]]
Output 2D masked array : [[-- 3e-05 -45.0 200000.0]]
Output 1D masked array : [-- 3e-05 -45.0 200000.0]