简体   繁体   English

使用2D索引(x,y,z)的2D列表递增3D计数器数组:Python Numpy Slicing

[英]Increment 3D array of counters from 2D list of indices (x,y,z) using: Python Numpy Slicing

I want to increment a 3D matrix (nparray) of counters from a 2D array of events (x,y,t) The code below works: 我想从事件(x,y,t)的2D数组中增加计数器的3D矩阵(nparray),以下代码起作用:

TOF_cube=np.zeros((324,324,4095),np.int32) #initialise a 3d array for whole data set

data = np.fromfile(f, dtype='<i2', count=no_I16) #read all events, x,y,t as 1D array
data=data.reshape(events,cols)
xpos=data[:,0]
ypos=data[:,1]
tpos=data[:,2]
i=0
while i < events:              
    TOF_cube[xpos[i],ypos[i],tpos[i]] += 1
    i+=1

To use slicing and indexing I replace my while loop with 要使用切片和索引,我将while循环替换为

    TOF_cube[xpos,ypos,tpos] += 1

But rather than copying the correct 4365520 number of events (via the while loop and independently checked) I only record 4365197. 但是,与其复制正确的事件数目4365520(通过while循环并独立检查),我只记录4365197。

Why is the slicing method loosing events? 切片方法为什么会丢失事件?

I am using exactly the same slices in the while loop and as an 'argument' to the index. 我在while循环中使用完全相同的切片,并将其用作索引的“参数”。

+= doesn't add twice if there are repeat indices. 如果有重复索引,则+=不会相加两次。

To get an equivalent output in a vectorized manner, you'll need np.add.at : 要以向量化方式获得等效输出,您需要np.add.at

np.add.at(TOF_cube, [xpos, ypos, tpos], 1)

As we do not know exactly what your data looks like it's hard to guess what the actual problem is. 由于我们不确定您的数据到底是什么样子,因此很难猜测出实际的问题是什么。 If this doesn't help please give an example that we can run ourselvs (ie without having the file f ). 如果这样做没有帮助,请举一个例子,我们可以运行我们的selvs(即,没有文件f )。

Suppose you have x_pos = [1,1,2,3,5] 假设您有x_pos = [1,1,2,3,5]

a = np.zeros(10)
for i in range(len(x_pos)):
    a[x_pos[i]]+=1
# gives a = array([ 0.,  2.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.])

However the other code 但是其他代码

a[x_pos]+=1
# gives a = array([ 0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.])

So if one of the indices occurs twice it is only updated once in the short version. 因此,如果其中一个索引出现两次,则在简短版本中仅更新一次。 Check whether this is actually the case in your xpos etc. 检查您的xpos等是否确实如此

PS: I did a slightly easier version, with only one dimension, but the rules stay the same. PS:我做了一个稍微简单的版本,只有一个维度,但是规则保持不变。

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

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