简体   繁体   English

如何找到所有点的2D numpy数组中的点大于参考数组中的对应点的百分比?

[英]How can I find the percentage of times that a point in a 2D numpy array is greater than the corresponding point in a reference array, for all points?

Python newbie here. Python新手在这里。 Given a list ( mylist ) of 2D numpy arrays, and a reference 2D numpy array ( refarr ), I'm looking for a way to create an array ( percentage_array ) in which each point (i,j) is the percentage of corresponding (i,j) points in the mylist arrays that are greater than [i,j] in refarr . 给定一个列表( mylist )2D numpy的阵列,和一个参考2D numpy的阵列( refarr ),我正在寻找一种方法来创建的阵列( percentage_array ),其中每个点(I,J)为对应的百分比( i,j)在mylist数组中的点大于refarr [i,j]。 I could do this by looping through all the points in the array and though the list, eg: 我可以通过遍历数组和列表中的所有点来做到这一点,例如:

percentage_array = numpy.empty(arr.shape)
for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        t = 0 
        f = 0
        for arr in mylist:
            if arr[i,j] > refarr[i,j]:
                t += 1 # counting the number of arrays for which [i,j] is true
            elif arr[i,j] <= refarr[i,j]:
                f += 1 # counting the number of arrays for which [i,j] is false
        percentage_array[i,j] = t/(t+f) # fraction of arrays which have 
                                        # arr[i,j] > refarr[i,j]

...but this is neither quick nor elegant (I'm dealing with large amounts of data). ...但这既不快速也不优雅(我正在处理大量数据)。 Are there better ways to do this? 有更好的方法可以做到这一点吗?

You can create a 3d array with 您可以使用创建3D数组

a = np.array(myList)

Then you can compare this array to your original one using broadcasting: 然后,您可以使用广播将该数组与原始数组进行比较:

a < refarr # gives a 3D array of booleans because refarr is broadcasted to a 3D array

and to count the percentage of values where the condition is met, you average on the first axis: 并计算满足条件的值的百分比,请在第一个轴上取平均值:

(a < refarr[None, :, :]).mean(axis = 0)

The main drawback of this approach is that you have to create an array a which may be big. 这种方法的主要缺点是必须创建一个可能很大的数组a Otherwise I'd consider treating arrays one by one. 否则我会考虑一一处理数组。

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

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