rpb
rpb

Reputation: 3299

How to efficiently create a N-D coordinate arrays using Numpy?

The idea is to create N-D coordinate that is divisible by 3. For simplicity, let the coordinate value to be only 1 and 2.

For a 6D coordinate, the following code can be used to generate 64 unique coordinate with value 1 and 2.

x=np.arange(1, 3, 1)
y=np.arange(1,3, 1)
z=np.arange(1,3, 1)
x_mesh, y_mesh, z_mesh=np.meshgrid(x,y,z)

coords = [(a2, b2, c2,) for a, b, c in zip(x_mesh, y_mesh, z_mesh) for a1, b1, c1 in zip(a, b, c) for a2, b2, c2 in zip(a1, b1, c1)]
arr = np.array ( coords )
sorted_array = arr [np.lexsort ( (arr [:, 1], arr [:, 0]) )] # Optional, but it is here for easy comparison with output manually produced with excel
rep_1 = np.repeat ( sorted_array, repeats=8, axis=0 )
t2 = np.tile ( sorted_array,
               (8, 1) )  # Optional, but it is here for easy comparison with output manually produced with excel
Table_6d = np.concatenate ( (rep_1, t2), axis=1 )

Similarly, the above code can be extended to produce a 9D coordinate, which yield 512 unique coordinate with value 1 and 2. The code to produced the 9D coordinate is shown below.

x=np.arange(1, 3, 1)
y=np.arange(1,3, 1)
z=np.arange(1,3, 1)
x_mesh, y_mesh, z_mesh=np.meshgrid(x,y,z)

coords = [(a2, b2, c2,) for a, b, c in zip(x_mesh, y_mesh, z_mesh) for a1, b1, c1 in zip(a, b, c) for a2, b2, c2 in zip(a1, b1, c1)]
arr = np.array(coords)
sorted_array =arr[np.lexsort((arr[:, 1], arr[:, 0]))]
r_a = np.repeat(sorted_array, repeats=8, axis=0)
t2 = np.tile(sorted_array,(8,1))
temp_tab=np.concatenate((r_a , t2 ), axis=1)
tvv = np.tile(temp_tab,(8,1))
T3 =tvv[np.lexsort((tvv[:, 5], tvv[:, 4], tvv[:, 3],tvv[:, 2], tvv[:, 1], tvv[:, 0]))] # Optional, but it is here for easy comparison with output manually produced with excel
t3_1 = np.tile(sorted_array,(64,1))

Table_9d=np.concatenate((T3 , t3_1 ), axis=1) 

Ultimately, I would like to have a higher dimension coordinate in the magnitude of thousand.

While it is possible to extend the code above, but I am not sure how to generalize it to handle higher dimension requirement.

Appreciate for any idea or reading material.

p.s., the main reason for creating such huge dimension is because I wanted to apply Pandas Vectorization.

Upvotes: 0

Views: 74

Answers (1)

Cory Nezin
Cory Nezin

Reputation: 1581

To create an arbitrary ND grid with meshgrid you just pass more lists. For example this creates a 9 Dimensional grid with coordinates 1-3

>>> arr = np.meshgrid(*[[1,2,3] for _ in range(9)])
>>> len(arr)
9
>>> arr[0].shape
(3, 3, 3, 3, 3, 3, 3, 3, 3)

Upvotes: 1

Related Questions