Select 'area' from a 2D array in python

后端 未结 1 375
独厮守ぢ
独厮守ぢ 2021-01-19 17:23

Is there a way to select a particular \'area\' of a 2d array in python? I can use array slicing to project out only one row or column but I am unsure about how to pick a \'s

相关标签:
1条回答
  • 2021-01-19 17:47

    If you are using the numpy library, you can use numpy's more advanced slicing to accomplish this like so:

    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]]
    

    (more info in the numpy docs)

    If you don't want to use numpy, you can use a list comprehension like this:

    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]]
    
    0 讨论(0)
提交回复
热议问题