在numpy数组中查找最常见的子数组

dra*_*ine 3 python numpy

示例数据:

array(
  [[ 1.,  1.],
   [ 2.,  1.],
   [ 0.,  1.],
   [ 0.,  0.],
   [ 0.,  0.]])
Run Code Online (Sandbox Code Playgroud)

期望的结果

>>> [0.,0.]
Run Code Online (Sandbox Code Playgroud)

ie)最常见的一对.

看似不起作用的方法:

使用statisticsnumpy数组是不可用的.

使用scipy.stats.modeas作为返回每个轴上的模式,例如,它给出了我们的示例

mode=array([[ 0.,  1.]])
Run Code Online (Sandbox Code Playgroud)

pim*_*314 8

您可以numpy使用该unique功能有效地执行此操作:

pairs, counts = np.unique(a, axis=0, return_counts=True)
print(pairs[counts.argmax()])
Run Code Online (Sandbox Code Playgroud)

返回: [ 0. 0.]

  • 任何人都需要知道,对于.argmax()〜"如果多次出现最大值,则返回与第一次出现相对应的索引." (2认同)
  • 注意`axis`参数仅在(最近的)`numpy` v.1.13中可用. (2认同)