Python 中矩阵的子集递增
我想增加矩阵的一小部分(变量)[下面的说明性代码] - 但通过循环运行它们似乎很草率且不优雅 - 我怀疑这是执行此计算的最慢方法。 我的想法之一是创建另一个由 1 组成的数组,其尺寸是我想要增加的(在下面的示例中为 2x3),并用零填充这个临时数组,使其与原始数组具有相同的尺寸。然后我可以将它们相加。
不确定如何在 numpy 中完成此填充 - 或者这是否是执行此计算的最高效方法?我想尝试尽可能地优化它。
>>> 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.]])
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.]])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地通过以下方式执行相同操作:
You can do the same simply by:
您还可以使用逻辑数组来访问子集的各个元素。当您的子集具有不规则形状时特别方便。
他们的表现也非常好。例如
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