开发者

Obtaining indexes of changed data between two numpy arrays

I have two 3d numpy arrays a1 and a2 where len(a1) == len(a2) and a1[x, y, z] = id

I'm using this code to find开发者_如何学JAVA out if there is changed data in any of the z layers

eq = a1 == a2
if eq.any():
    #find the indexes of the changed data

as the comment and title says I need to find the indexes of the changed data. basically I have a list of objects that correspond the the positions in the array and I need to update those objects based on the id pulled form the array. I want to do this as fast as possible as this list can get REALLY large possibly more than 120,000 entries. but only a hundred or so of these entries are likely to change at any one time. as such I'd like to obtain a list of the changed indexes so I can call the object at that index and update it.

I do need to maintain the three components of the index

is there a way to do this without looping through the list? perhaps with numpy.nonzero()


Two more options:

np.argwhere(a1!=a2)
np.where(a1!=a2)

They both do the same thing but produce results in different formats (one suitable for indexing the arrays, the other more readable)


I didn't understand the specifics of your question (e.g., the size/shape of your array); this solution should be general enough though. In any event, it's loop-less:

# two 2d arrays
x = NP.random.randint(0, 10, 20).reshape(5, 4)
y = NP.random.randint(0, 10, 20).reshape(5, 4)

ndx1, ndx2 = NP.nonzero((x - y))

# all indices in which the values of x & y differ, each index is a tuple
ndx = zip(ndx1, ndx2)  

# you can also use argwhere, returns each index as a 1d array vs. tuple:
NP.argwhere(dxy)

# finally, just generating an array the same size as the diff array with e.g.,
# '1' for each diff element and '0' for each non-diff:
dxy = x - y
NP.where(dxy=0, 0, 1)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜