python - 使用 2d numpy 数组切片 3d numpy 数组

标签 python arrays numpy slice

是否可以使用 2d 数组对 3d 数组进行切片。我假设它可以完成,但需要您必须指定轴?

如果我有 3 个数组,这样:

A = [[1,2,3,4,5],
     [1,3,5,7,9],
     [5,4,3,2,1]] # shape (3,5)

B1 = [[1],
      [2],
      [3]] # shape (3, 1) 

B2 = [[4],
      [3],
      [4]] # shape (3,1)

是否可以像这样使用 B1 和 B2 对 A 进行切片:

Out = A[B1:B2]

这样它会返回我:

Out = [[2,3,4,5],
       [5, 7],
       [2, 1]]

或者,如果切片在 Out 中创建不同长度的数组,这将不起作用吗?

最佳答案

Numpy 针对具有固定维度的同构数字数组进行了优化,因此它不支持不同的行或列大小。

但是你可以通过使用数组列表来实现你想要的:

Out = [A[i, B1[i]:B2[i]+1] for i in range(len(B1))]

关于python - 使用 2d numpy 数组切片 3d numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732254/

相关文章:

python - 函数声明时出现 Theano OSError

c++ - 在扩展模块中为用户定义的 python 类 boost Python to_python_converter

python - 在 django 中获取基于时间的模型统计信息

python - 不和谐.错误.禁止 : 403 FORBIDDEN (error code: 50013): Missing Permissions

arrays - 如何在 perl 数组中对序列号进行分组?

使用数组时出现 Java NullPointerException

python - 2 个向量中所有点之间的欧氏距离

python - Selenium python 单击按钮

c - array [] 括号内的 static 关键字

python - Pandas:数据帧错误 - 传递了 2 列,传递的数据有 3 列