我有两个非常长的1D矩阵(这里用更短的x和y矩阵表示)。我想创建两个新的矩阵X和Y,我将根据以下两个条件相互绘制:
在两个矩阵中,我想保留索引的元素值,其中x< 7和y!= -9999我想用标志值-9999替换所有其他元素值。
目前,我可以通过一个非常缓慢的循环来实现这个目标:
# Create some fake data:
x = np.arange(10)
y = np.arange(0, 100, 10)
y[2] = -9999.0
y[5] = -9999.0
y[8] = -9999.0
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y
array([0, 10, -9999, 30, 40, -9999, 60, 70, -9999, 90])
# Loop over the data
for idx in np.arange(10):
# Keep matrice elements in both matrices satisfying:
if x[idx] < 7 and y != -9999:
x[idx] = [idx]
y[idx] = y[idx]
# Replace all other elements with the flag -9999
else:
x[idx] = -9999
y[idx] = -9999
x
array([0, 1, -9999, 3, 4, -9999, 6, -9999, -9999, -9999])
y
array([0, 10, -9999, 30, 40, -9999, 60, -9999, -9999, -9999])
x_rm_flags = filter(lambda a: a != -9999.0, x) # Removes all flagged values == -9999.0, thus shorting the matrix and converts it into a list
X = np.zeros([len(x_rm_flags),1]) # Convert the list into an array. Step 1: Create the (zero-)array
X[:,0] = x_rm_flags[:] # Convert the list into an array. Step 2: Fill the array with its correct values
y_rm_flags = filter(lambda a: a != -9999.0, y) # Removes all flagged values == -9999.0, thus shorting the matrix and converts it into a list
Y = np.zeros([len(y_rm_flags),1]) # Convert the list into an array. Step 1: Create the (zero-)array
Y[:,0] = y_rm_flags[:] # Convert the list into an array. Step 2: Fill the array with its correct values
我想要的是做循环所做的事情,但是以更有效的方式,我希望python可能有一些内置函数。 (例如,我考虑过使用numpy.where和/或numpy.select,但我还没有弄清楚如何实现和使用它们 - 如果它们甚至是一个很好的方法。)< / p>
有没有人对如何提高我的代码效率有任何建议?