简体   繁体   English

查找数组Numpy中非零元素的模式

[英]Find mode of non-zero elements in array Numpy

What is most efficient way to find the mode per row in a multi-dimensional array of the non-zero elements? 在非零元素的多维数组中查找每行模式的最有效方法是什么?

For example: 例如:

[
 [0.  0.4 0.6 0.  0.6 0.  0.6 0.  0.  0.6 0.  0.6 0.6 0.6 0.  0.  0.  0.6
     0.  0.  0.  0.  0.  0.  0.  0.  0.5 0.6 0.  0.  0.6 0.6 0.6 0.  0.  0.6
     0.6 0.6 0.  0.5 0.6 0.6 0.  0.  0.6 0.  0.6 0.  0.  0.6],
 [0.  0.1 0.2 0.1 0.  0.1 0.1 0.1 0.  0.1 0.  0.  0.  0.1 0.1 0.  0.1 0.1
 0.  0.1 0.1 0.1 0.  0.1 0.1 0.1 0.  0.1 0.2 0.  0.1 0.1 0.  0.1 0.1 0.1
 0.  0.2 0.1 0.  0.1 0.  0.1 0.1 0.  0.1 0.  0.1 0.  0.1]
]

The mode of the above is [0, 0.1] , but ideally we want to return [0.6, 0.1] . 上面的模式是[0, 0.1] ,但理想情况下我们想返回[0.6, 0.1]

You would use the same method as this question (mentioned in the comments by @yatu), but instead make a call to the numpy.nonzero() method. 您将使用与问题相同的方法(在@yatu的注释中提到),但是调用numpy.nonzero()方法。

To get just the non-zero elements, we can just call the nonzero method, which will return the indices of the non-zero elements. 为了只获取非零元素,我们可以调用nonzero方法,该方法将返回非零元素的索引。 We can do this using this command, if a is a numpy array: 如果a是一个numpy数组,我们可以使用以下命令执行此操作:

a[nonzero(a)]

Example finding the mode (building off code from the other answer): 查找模式的示例(从其他答案构建代码):

import numpy as np
from scipy import stats

a = np.array([
    [1, 0, 4, 2, 2, 7],
    [5, 2, 0, 1, 4, 1],
    [3, 3, 2, 0, 1, 1]]
)

def nonzero_mode(arr):
    return stats.mode(arr[np.nonzero(arr)]).mode

m = map(nonzero_mode, a)
print(m)

If you wanted to get the mode of each row, just use a loop through the array: 如果要获取每一行的模式,只需使用遍历数组的循环即可:

for row in a:
   print(nonzero_mode(row))

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

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