如何使用numpy?如何快速在二维矩阵中选择子矩阵。
我有一个 7×7 矩阵,我不想使用循环来快速切出子矩阵。
matrix= array([[ 0, 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34],
[35, 36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47, 48]])
sub_matrix = array([[1,2,3], [16,17,18], [28,29,30], [39,40,41]])
其实这个矩阵很大。我有每行的切片列表和每列开头的切片列表。直接指定所有行的列切片列表是非常困难的。
我尝试了以下方法,但它给了我错误:IndexError:形状不匹配:索引数组无法与形状(4,)(4,3)一起广播
slice_row = [0, 2, 4, 5]
slice_col_start = [1,2,0,4]
interval = 3
slice_col = [np.arange(x,x+interval) for x in slice_col_start]
matrix[slice_row, np.r_[slice_col]]
I have a 7×7 matrix and I don't want to use the loop to quickly slice out a submatrix.
matrix= array([[ 0, 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34],
[35, 36, 37, 38, 39, 40, 41],
[42, 43, 44, 45, 46, 47, 48]])
sub_matrix = array([[1,2,3], [16,17,18], [28,29,30], [39,40,41]])
In fact, this matrix is very large. I have a list of slices per row and a list of slices at the beginning of each column. It is very difficult to specify directly the columns slice list for all rows.
I tried the following method, but it gave me error:IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (4,) (4,3)
slice_row = [0, 2, 4, 5]
slice_col_start = [1,2,0,4]
interval = 3
slice_col = [np.arange(x,x+interval) for x in slice_col_start]
matrix[slice_row, np.r_[slice_col]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您有索引可以执行:
输出:
If you have the indices you could do:
output:
由于间隔是固定的,因此我们可以使用
linspace
用一个调用来创建所有列索引:然后,这只是索引的问题:
或使用广播添加:
如果间隔因行而变化,我们将不得不使用迭代形式获取完整的列索引列表。
Since the interval is fixed, we can use
linspace
to create all column indices with one call:Then it's just a matter of indexing:
Or use broadcasted addition:
If the interval varies by row, we will have to use form of iteration to get the full list of column indices.
可以通过
np.take_along_axis
来实现。如果给出cols
数组:It can be achieved by
np.take_along_axis
. If thecols
array be given:感谢凯文,我想出了一个解决方案
输出
Thanks to Kevin, I came up with a solution
output