开发者

Incrementing sub-sets of matrices in Python

I want to increment a small subsection (variable) of an matrix [illustrative code below] - but running over them by loops seems sloppy and inelegant -- and I suspect is the slowest way to do this calc. One of the ideas I had was to create another array of ones, of the dimensions that i want to increment (2x3 in example below) and to pad this temporary array with zeros so it was of the same dimensions as the original. I could then sum them.

Not sure how to accomplish this padding in numpy - or if that is the most performant way of doing this calculation? I'd like to try and optimize this as much as possible.

>>> import numpy as np    
>>> a = np.zeros((10,10))
>>> for i in range(3,5):
...     for x in range(4,7):
...         a[i][x] += 1
>>> a
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0., 开发者_如何学运维 0.],
       [ 0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])


You can do the same simply by:

 a[3:5,4:7] += 1


You can use also logical arrays for accessing individual elements of your subset. Especially handy when your subset has irregular shape.

Also they perform very well. For example

In []: M= randn(2000, 2000)
In []: timeit M[M< 0]+= 10
1 loops, best of 3: 42.1 ms per loop
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜