Create a two-dimensional array with 2d coordinates as elements in numpy

Asked 2 years ago, Updated 2 years ago, 49 views

Hello, I'm asking you a question because I encountered a difficulty in creating an array with numpy.

Now we want to create a two-dimensional array with two-dimensional coordinates (x, y) as an element.

I'm worried that if I combine the useful functions of numpy well, I can easily create this arrangement without using a for statement.

If you have experienced a similar problem and solved it, or if you know a useful function, please leave a comment or answer.

Thank you :)

numpy python grid

2022-09-22 11:37

2 Answers

It is possible simply with list compliance as below. You don't have to use the list compliance. You can just use two for statements. It looks simple because it's in one line.

And, although we didn't use the example, itertools also has a function called product.

>>> from pprint import pprint
>>> l = [ (x, y) for x in (0, 1, 2, 3) for y in (0, 1, 2, 3) ]
>>> pprint(l)
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (1, 0),
 (1, 1),
 (1, 2),
 (1, 3),
 (2, 0),
 (2, 1),
 (2, 2),
 (2, 3),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 3)]
>>> l = [ [ (x, y) for x in (0, 1, 2, 3) ] for y in (0, 1, 2, 3) ]
>>> pprint(l)
[[(0, 0), (1, 0), (2, 0), (3, 0)],
 [(0, 1), (1, 1), (2, 1), (3, 1)],
 [(0, 2), (1, 2), (2, 2), (3, 2)],
 [(0, 3), (1, 3), (2, 3), (3, 3)]]
>>> import pandas as pd
>>> import numpy as np
>>> ll = np.array(l)
>>> ll
array([[[0, 0],
        [1, 0],
        [2, 0],
        [3, 0]],

       [[0, 1],
        [1, 1],
        [2, 1],
        [3, 1]],

       [[0, 2],
        [1, 2],
        [2, 2],
        [3, 2]],

       [[0, 3],
        [1, 3],
        [2, 3],
        [3, 3]]])
>>> ll[0]
array([[0, 0],
       [1, 0],
       [2, 0],
       [3, 0]])


2022-09-22 11:37

I think I can answer it myself lol I'd like to share the method I found.

import numpy as np

# (5) Generating a numpy array of sizes
x = np.array([i for i in range(5)])
y = np.array([j for j in range(5)])

# (5, 5) Create a numpy array of sizes
x = np.tile(x, (5, 1))
y = np.tile(y.reshape(5, 1), (5))

# Create a numpy array of sizes (5, 5, 2)
xy = np.dstack((x, y))

Used numpy's tile and dstack functions.

The direction of the code I originally wanted is this format, so I'm going to write it in detail :)

Thank you


2022-09-22 11:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.