数组切片数

时间:2020-08-08 11:18:47

标签: python python-3.x numpy numpy-slicing

r =  np.arange(36)
r.resize((6,6))

output:
[[ 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]]

我的问题是:

  1. 如何从完整矩阵中提取子数组?

示例:

 [[14 15],                                                                            
  [20 21]]
  1. resize中的reshapenumpy语法之间有什么区别?

1 个答案:

答案 0 :(得分:1)

  1. 您可以通过sliceing操作提取数组的所需部分:
r =  np.arange(36)
r = r.reshape((6, 6))    
r[2:4, 2:4]
  • numpy.resize收到要调整大小的numpy.arraynew_shape(类型为int的{​​{1}}或tuple),它们分别表示调整大小后的数组的形状,并返回调整后的大小ints
  • numpy.reshape收到要重塑的numpy.array和一个numpy.array(又是newshape的{​​{1}}或int类型的),表示输出数组的所需形状,并返回经过重整的tuple

这两种方法之间的主要区别是ints填充输出以匹配所需的形状,而numpy.array将在所请求的形状不适合数据时抛出错误。

例如:

resize

如果您使用reshape,它将输出所需的数组:

r =  np.arange(36)
r = r.reshape((6, 1))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-165-36ecb32eda6e> in <module>
      1 r =  np.arange(36)
----> 2 r = r.reshape((6, 1))
      3 r[2:4, 2:4]

ValueError: cannot reshape array of size 36 into shape (6,1)
相关问题