本文介绍了计算二维阵列上拒绝特殊值(知道索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开始在Python和... ...编码
我想要做一个二维数组的计算与拒绝特殊值(我知道它的数组中的坐标)与array_valuesreject
I'm beginning in Python and...coding...I m trying to do calculations on a 2D array with reject special values (i know its coordinates in the array) with array_valuesreject
作为例子:
import numpy as np
#A array of the points I must reject
#The first column reprensents the position in Y and the second the position in X
#of 2D array below
array_valuesreject = np.array([[1.,2.],[2.,3.], [3.,5.],[10.,2.]])
#The 2D array :
test_array = np.array([[ 3051.11, 2984.85, 3059.17],
[ 3510.78, 3442.43, 3520.7 ],
[ 4045.91, 3975.03, 4058.15],
[ 4646.37, 4575.01, 4662.29],
[ 5322.75, 5249.33, 5342.1 ],
[ 6102.73, 6025.72, 6127.86],
[ 6985.96, 6906.81, 7018.22],
[ 7979.81, 7901.04, 8021. ],
[ 9107.18, 9021.98, 9156.44],
[ 10364.26, 10277.02, 10423.1 ],
[ 11776.65, 11682.76, 11843.18]])
#So I would like to apply calculation on 2D array without taking account of the
#list of coordinates defined above and i would like to keep the same dimensions array!
#(because it s represented a matrix of detectors)
#Create new_array to store values
#So I try something like that....:
new_array = numpy.zeros(shape=(test_array.shape[0],test_array.shape[1]))
for i in range(test_array.shape[0]):
if col[i] != (array_valuesreject[i]-1):
for j in range(test_array.shape[1]):
if row[j] != (array_valuesreject[j]-1):
new_array[i,j] = test_array[i,j] * 2
感谢您的帮助!
推荐答案
这是使用屏蔽数组一个很好的案例。你要掩盖你想在计算中忽略的坐标:
This is a good case to use a masked array. You have to mask the coordinates you want to ignore in the calculation:
#NOTE it is an array of integers
array_valuesreject = np.array([[1, 2], [2, 2], [3, 1], [10, 2]])
i, j = array_valuesreject.T
mask = np.zeros(test_array.shape, bool)
mask[i,j] = True
m = np.ma.array(test_array, mask=mask)
在打印屏蔽数组 M
:
masked_array(data =
[[3051.11 2984.85 3059.17]
[3510.78 3442.43 --]
[4045.91 3975.03 --]
[4646.37 -- 4662.29]
[5322.75 5249.33 5342.1]
[6102.73 6025.72 6127.86]
[6985.96 6906.81 7018.22]
[7979.81 7901.04 8021.0]
[9107.18 9021.98 9156.44]
[10364.26 10277.02 10423.1]
[11776.65 11682.76 --]],
mask =
[[False False False]
[False False True]
[False False True]
[False True False]
[False False False]
[False False False]
[False False False]
[False False False]
[False False False]
[False False False]
[False False True]],
fill_value = 1e+20)
和计算将仅在非掩蔽值来执行,以使得可以执行
and the calculations will only be performed for the non-masked values, such that you can do:
new_array = m * 2
要得到你想要的东西。
这篇关于计算二维阵列上拒绝特殊值(知道索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!