Increment Numpy multi-d array with repeated indices

℡╲_俬逩灬. 提交于 2019-12-18 05:12:52

问题


I'm interested in the multi-dimensional case of Increment Numpy array with repeated indices.

I have an N-dimensional array and a set N index arrays, who's values I want to increment. The index arrays might have have repeated entries.

Without repeats, the solution is

a = arange(24).reshape(2,3,4)
i = array([0,0,1])
j = array([0,1,1])
k = array([0,0,3])
a[i,j,k] += 1

With repeats, (ex. j=array([0,0,2]) ), I'm unable to make numpy increment the replicates.


回答1:


How about this:

import numpy as np
a = np.zeros((2,3,4))
i = np.array([0,0,1])
j = np.array([0,0,1])
k = np.array([0,0,3])

ijk = np.vstack((i,j,k)).T
H,edge = np.histogramdd(ijk,bins=a.shape)
a += H  



回答2:


I don't know if there is an easier solution with direct array indexing, but this works:

for x,y,z in zip(i,j,k):
    a[x,y,z] +=1


来源:https://stackoverflow.com/questions/7433142/increment-numpy-multi-d-array-with-repeated-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!