[英]extracting a subarray from an array in python using numpy
if this is given on a homework assignment: 如果这是在家庭作业上给出的:
import numpy as np
room_matrix = \
np.array(
[[6, 3, 4, 1],
[5, 2, 3, 2],
[8, 3, 6, 2],
[5, 1, 3, 1],
[10, 4, 7, 2]])
and the task is: 任务是:
write an expression that retrieves the following submatrix from room_matrix: 编写一个表达式,该表达式从room_matrix中检索以下子矩阵:
array([[2,3],
[3,6]])
I have done this so far: 到目前为止,我已经做到了:
a=room_matrix[1,1:3]
b=room_matrix[2,1:3]
then I print "a" and "b" and the output is: 然后我打印“ a”和“ b”,输出是:
[2 3]
[3 6]
but I want them to be executed as an actual subarray like so: 但我希望将它们作为实际的子数组执行,如下所示:
array([[2,3],
[3,6]])
Can I concatenate "a" and "b"? 我可以串联“ a”和“ b”吗? Or is there another way to extract a sub array so that the output actually shows it as an array, and not just me printing two splices?
还是有另一种方法来提取子数组,以便输出实际上将其显示为一个数组,而不仅仅是我打印两个接头? I hope this makes sense.
我希望这是有道理的。 Thank you.
谢谢。
You needn't do that in two lines. 您无需两行就可以做到。 Numpy allows you to splice within a single statement, like this:
Numpy允许您在单个语句中进行拼接,如下所示:
room_matrix[1:3, 1:3]
#will slice rows starting from 1 to 2 (row numbers start at 0), likewise for columns
How about this: 这个怎么样:
In [1]: import numpy as np
In [2]: room_matrix = \
...: np.array(
...: [[6, 3, 4, 1],
...: [5, 2, 3, 2],
...: [8, 3, 6, 2],
...: [5, 1, 3, 1],
...: [10, 4, 7, 2]])
In [3]: room_matrix
Out[3]:
array([[ 6, 3, 4, 1],
[ 5, 2, 3, 2],
[ 8, 3, 6, 2],
[ 5, 1, 3, 1],
[10, 4, 7, 2]])
In [4]: room_matrix[1:3, 1:3]
Out[4]:
array([[2, 3],
[3, 6]])
The question has already been answered, so just throwing it out there, but, indeed, you could use np.vstack
to "concatenate" your a and b matrices to get the desired result: 这个问题已经被回答了,所以就把它扔出去,但是,实际上,您可以使用
np.vstack
来“连接”您的a和b矩阵以获得所需的结果:
In [1]: import numpy as np
In [2]: room_matrix = \
...: np.array(
...: [[6, 3, 4, 1],
...: [5, 2, 3, 2],
...: [8, 3, 6, 2],
...: [5, 1, 3, 1],
...: [10, 4, 7, 2]])
In [3]: a=room_matrix[1,1:3]
In [4]: b=room_matrix[2,1:3]
In [5]: np.vstack((a,b))
Out[5]:
array([[2, 3],
[3, 6]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.