简体   繁体   English

在数组中查找特定值

[英]Find specific values inside array

I'm trying to insert conditioned values in an array into an empty array in exact position. 我正在尝试将数组中的条件值插入到精确位置的空数组中。

empty_array = np.zeros([40,100])
for x in range (1,24):
    array[x,:,:] #which is also sized 40x100
    if the_values_in_the_array < 0.25:
         the_values_in_the_array = 0
    empty_array = empty_array + array [x,:,:]

Which syntax should I use for this logic? 我应该使用哪种语法来实现这种逻辑? And how should I scan the_values_in_the_array to find the conditioned values? 我应该如何扫描the_values_in_the_array来查找条件值?

empty_array = np.zeros([40,100])
array = np.random.rand(24,40,100)

array[array<0.25]=0 # change all the values which is <0.25 to 0
for x in range(1,24):
    empty_array += array[x,:,:]

I think the is the operation you are trying to do. 我认为这是你要做的操作。 I suggest using the np.where routine for setting values less than 0.25 to zero. 我建议使用np.where例程将小于0.25的值设置为零。 Then you can sum over just the first dimension of the array to get the output array you are looking for. 然后,您可以只计算数组的第一个维度,以获得您正在寻找的输出数组。 I reduced the dimensions of the problem for the example. 我减少了示例中问题的维度。

import numpy as np

vals = np.random.random([24, 2, 3])
vals_filtered = np.where(vals < 0.25, 0.0, vals)
out = vals_filtered.sum(axis=0)
print("First sample array has the slice vals[0,:,:]:\n{}\n".format(vals[0, :, :]))
print("First sample array with vals>0.25 set to 0.0:\n{}\n".format(vals_filtered[0, :, :]))
print("Output array is the sum over the first dimension:\n{}\n".format(out))

This returns the following output. 这将返回以下输出。

First sample array has the slice vals[0, :, :]: 
[[ 0.16272567  0.13695067  0.5954866 ]
 [ 0.50367823  0.8519252   0.3000367 ]]

First sample array with vals>0.25 set to 0.0: 
[[ 0.          0.          0.5954866 ]
 [ 0.50367823  0.8519252   0.3000367 ]]

Output array is the sum over the first dimension: 
[[ 11.12707813  12.04175706  11.5812803 ]
 [ 13.73036272   9.3988165   12.41808745]]

Is this the calculation you were looking for? 这是你要找的计算吗? Calling vals.sum(axis=0) is a faster way to do the operation. 调用vals.sum(axis=0)是一种更快速的操作方式。 It is usually better to call numpy's built-in array routines, as opposed to an explicit for loop. 调用numpy的内置数组例程通常更好,而不是显式的for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM