【问题标题】:Select 'area' from a 2D array in python从python中的二维数组中选择“区域”
【发布时间】:2014-09-02 00:34:36
【问题描述】:

有没有办法在 python 中选择二维数组的特定“区域”? 我可以使用数组切片来仅投影一行或一列,但我不确定如何从大型二维数组中选择一个“子数组”。 提前致谢 杰克

【问题讨论】:

  • 你的意思是像array[row1:row2, col1:col2]这样的东西吗?

标签: python arrays


【解决方案1】:

如果您使用numpy 库,则可以使用numpy 的更高级的切片来完成此操作,如下所示:

import numpy as np
x = np.array([[1, 2, 3, 4], 
              [5, 6, 7, 8], 
              [9, 10, 11, 12]])

print x[0:2,  2:4]
#       ^^^   ^^^
#       rows  cols

# Result:
[[3 4]
 [7 8]]

(更多信息在numpy docs

如果您不想使用numpy,可以使用这样的列表推导:

x = [[1, 2, 3, 4], 
     [5, 6, 7, 8], 
     [9, 10, 11, 12]]

print [row[2:4] for row in x[0:2]]
#          ^^^      ^^^ select only rows of index 0 or 1
#          ^^^ and only columns of index 2 or 3

# Result:
[[3, 4], 
 [7, 8]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 2014-11-17
    • 2018-11-11
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多