本文介绍了将bincount应用于2D numpy数组的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将"c = 1"应用于轴= 1"?所需的结果将与列表理解相同:

Is there a way to apply bincount with "axis = 1"? The desired result would be the same as the list comprehension:

import numpy as np
A = np.array([[1,0],[0,0]])
np.array([np.bincount(r,minlength = np.max(A) + 1) for r in A])

#array([[1,1]
#       [2,0]])

推荐答案

np.bincount 不适用于沿特定轴的2D阵列.为了通过对np.bincount的单个矢量化调用获得所需的效果,可以创建ID的一维数组,以便即使元素相同,不同的行也将具有不同的ID.当使用具有这些ID的np.bincount单个调用时,这将使不同行中的元素不会合并在一起.因此,这样的ID数组可以在想到linear indexing的前提下创建,就像这样-

np.bincount doesn't work with a 2D array along a certain axis. To get the desired effect with a single vectorized call to np.bincount, one can create a 1D array of IDs such that different rows would have different IDs even if the elements are the same. This would keep elements from different rows not binning together when using a single call to np.bincount with those IDs. Thus, such an ID array could be created with an idea of linear indexing in mind, like so -

N = A.max()+1
id = A + (N*np.arange(A.shape[0]))[:,None]

然后,将ID馈送到np.bincount,最后重新塑形为2D-

Then, feed the IDs to np.bincount and finally reshape back to 2D -

np.bincount(id.ravel(),minlength=N*A.shape[0]).reshape(-1,N)

这篇关于将bincount应用于2D numpy数组的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 06:23