Youngsup Kim
Youngsup Kim

Reputation: 2235

Convert coordinates in a region into a numpy array in Python

I have a rectangular region, where the lower left (min) and upper right (max) coordinates. I want to make a Numpy array that consists of coordinates in the region. For example, the min and max are (3, 8) and max (0, 6), respectively. The numpy array I want to make is

enter image description here

Additionally, I have a requirement that the grid in the region may be smaller than 1. For example, 0.5 makes X = [[3.0, 0] [3.5, 0] [4.0, 0] [4.5, 0] ...]]

Upvotes: 0

Views: 894

Answers (1)

kennytm
kennytm

Reputation: 523184

You could use numpy.mgrid:

>>> numpy.mgrid[3:8, 0:6].T
array([[[3, 0],
        [4, 0],
        [5, 0],
        [6, 0],
        [7, 0]],

       [[3, 1],
        [4, 1],
        [5, 1],
        [6, 1],
        [7, 1]],

        ...

       [[3, 5],
        [4, 5],
        [5, 5],
        [6, 5],
        [7, 5]]])

If you want a "flat" array of tuples, you can reshape it:

>>> numpy.mgrid[3:8, 0:6].T.reshape((-1, 2))
array([[3, 0],
       [4, 0],
       [5, 0],
       [6, 0],
       [7, 0],
       [3, 1],
       ...
       [6, 5],
       [7, 5]])

Upvotes: 4

Related Questions