简体   繁体   English

在切片二维 python numpy 数组中检索 null 值

[英]Retrieving null value in slicing 2d python numpy array

I need to slice a python numpy array for multiplication.我需要对 python numpy 数组进行切片以进行乘法运算。 The slicing I need to be in the below format我需要的切片格式如下

    first_slice_matrixA=[0,1]
    second_slice_matriA=[2,3]
    first_slice_matrixB=[0,2]
    second_slice_matrixB=[1,3]

Below is my code for slicing.下面是我的切片代码。 For the first slice its working but for second it returns a null array.对于第一个切片它的工作,但第二个它返回一个 null 数组。

   matrix_A = np.arange(4).reshape(2,2)
   matrix_B=np.arange(4).reshape(2,2)
   A_1=matrix_A[0:1, 0:2]
   A_2=matrix_A[1:1, 0:2]
   print(A_2)

Thank you for your help谢谢您的帮助

When you use same index for start and stop, the slice is empty, whatever the index is.当您对开始和停止使用相同的索引时,无论索引是什么,切片都是空的。 You'd do the following so see your values您将执行以下操作,以查看您的价值观

  • first index is vertical slicing, so it selects 'rows'第一个索引是垂直切片,所以它选择“行”
  • second index is horizontal slicing, so it selects 'columns'第二个索引是水平切片,所以它选择“列”
m = np.arange(4).reshape(2,2)

# horizontal
print(m[0:1, :]) # [[0 1]]
print(m[1:2, :]) # [[2 3]]

# vertical
print(m[:, 0:1]) # [[0] [2]]
print(m[:, 1:2]) # [[1] [3]]

Note that here, because of size 2注意这里,因为大小 2

m[0:1, :] == m[:1, :]
m[1:2, :] == m[1:, :]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM