简体   繁体   English

轴0上的numpy个计数元素与另一个数组中的值匹配

[英]numpy count elements across axis 0 matching values from another array

Given a 3D array such as: 给定一个3D数组,例如:

array = np.random.randint(1, 6, (3, 3, 3))

and an array of maximum values across axis 0: 以及沿轴0的最大值数组:

max_array = array.max(axis=0)

Is there a vectorised way to count the number of elements in axis 0 of array which are equal to the value of the matching index in max_array? 是否存在一种矢量化的方法来计算数组中轴0上等于max_array中匹配索引值的元素数量? For example, if array contains [1, 3, 3] in one axis 0 position, the output is 2, and so on for the other 8 positions, returning an array with the counts. 例如,如果数组在一个轴0位置包含[1、3、3],则输出为2,对于其他8个位置,依此类推,返回带有计数的数组。

To count the number of values in x which equal the corresponding value in xmax , you could use: 要计算x中等于xmax相应值的值的数量,可以使用:

(x == xmax).sum(axis=0)

Note that since x has shape (3,3,3) and xmax has shape (3,3), the expression x == xmax causes NumPy to broadcast xmax up to shape (3,3,3) where the new axis is added on the left. 请注意,由于x具有形状(3,3,3)和xmax具有形状(3,3),表达式x == xmax导致NumPy 广播 xmax直到形状(3,3,3),其中添加了新轴在左边。


For example, 例如,

import numpy as np
np.random.seed(2015)
x = np.random.randint(1, 6, (3,3,3))
print(x)
# [[[3 5 5]
#   [3 2 1]
#   [3 4 1]]

#  [[1 5 4]
#   [1 4 1]
#   [2 3 4]]

#  [[2 3 3]
#   [2 1 1]
#   [5 1 2]]]

xmax = x.max(axis=0)
print(xmax)
# [[3 5 5]
#  [3 4 1]
#  [5 4 4]]

count = (x == xmax).sum(axis=0)
print(count)
# [[1 2 1]
#  [1 1 3]
#  [1 1 1]]

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

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