计算矩阵元素的出现次数

2024-09-28 01:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

Mn分别为dxd-和d-整数的一维整数数组。我想计算形式为(n(I),n(j),M(I,j))的三元组的数目。因此,我需要一个numpy数组,这样每个条目都会计算这样一个三元组的出现次数。你知道吗

编辑:M是对称的,我不想用I=j来计算三元组

我目前正在使用itertools.product(for loop over all pairs)和numpy.bincount来实现这一点,但是速度太慢了。有没有更聪明的方法,可能是使用numpy?你知道吗


Tags: numpyloop编辑for条目整数数组product
2条回答

让:

M=np.random.randint(0,3,(10,10))
n=np.random.randint(0,3,10)

做三倍并下降i=j:

x,y=np.meshgrid(n,n)
a=np.dstack((x,y,M)).reshape(-1,3)
au=a[a [:,0]!=a[:,1]]   # i<>j

unique的问题是它只使用1D数组。一个解决方案是在字符串中转换行:这样可以确保延迟比较,而且通常比较快。你知道吗

c=np.frombuffer(au,dtype='S12')   # 12 is  3*n.itemsize

_,indices,counts=np.unique(c,return_index=True,return_counts=True)

result=np.vstack((counts,au[indices].T)) # count first.

##
array([[1, 2, 5, 3, 4, 1, 4, 4, 3, 4, 9, 1, 3, 4, 9, 3, 4],
       [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
       [1, 1, 1, 2, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0, 1, 1, 1],
       [0, 1, 2, 0, 1, 2, 0, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], dtype=int64)

如果整数像这里这样小(<;4),则可以显示结果,以便res[n(i),n(j),M(i,j)]给出计数:

res=np.zeros((3,3,3),int) 
res[list(zip(*au[indices]))]=counts

由于数组包含整数,因此可以将每个三元组视为可线性索引的元素。这里有一种方法,它将哲学铭记在心,从而避免循环,就像这样-

# Form n(i) x n(j) array and then append with "columnar" M(i,j) array
nn_arr = n[np.array(list(itertools.product(range(5), repeat=2)))]

nn_M_arr = np.concatenate((nn_arr,M.reshape(-1,1)),axis=1)

# Get linear indices version
dims = nn_M_arr.max(0)+1
lidx = np.ravel_multi_index(nn_M_arr.T,dims)

# Get unique indices and the counts
_, idx, counts = np.unique(lidx,return_index=True,return_counts=True)

# Get corresponding unique triplets using unique indices and zip with counts
out = zip(map(tuple,nn_M_arr[idx]),counts)

样本运行-

In [206]: M
Out[206]: 
array([[1, 0, 0, 2, 0],
       [1, 1, 2, 0, 2],
       [0, 0, 2, 0, 1],
       [2, 1, 2, 0, 2],
       [1, 1, 1, 1, 0]])

In [207]: n
Out[207]: array([0, 1, 1, 1, 2])

In [208]: out
Out[208]: 
[((0, 0, 1), 1),
 ((0, 1, 0), 2),
 ((0, 1, 2), 1),
 ((0, 2, 0), 1),
 ((1, 0, 0), 1),
 ((1, 0, 1), 1),
 ((1, 0, 2), 1),
 ((1, 1, 0), 4),
 ((1, 1, 1), 2),
 ((1, 1, 2), 3),
 ((1, 2, 1), 1),
 ((1, 2, 2), 2),
 ((2, 0, 1), 1),
 ((2, 1, 1), 3),
 ((2, 2, 0), 1)]

相关问题 更多 >

    热门问题