如何使用 Numpy 高效创建 ND 坐标数组?

其想法是创建可被 3 整除的 ND 坐标。为简单起见,让坐标值仅为 1 和 2。


对于 6D 坐标,可以使用以下代码生成 64 个唯一坐标,值为 1 和 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 )

类似地,上面的代码可以扩展为生成 9D 坐标,从而生成 512 个值为 1 和 2 的唯一坐标。生成 9D 坐标的代码如下所示。


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) 

最终,我希望有一个千量级的更高维度坐标。


虽然可以扩展上面的代码,但我不确定如何概括它来处理更高的维度要求。


感谢任何想法或阅读材料。


ps,创建这么大维度的主要原因是因为我想应用 Pandas Vectorization。


一只萌萌小番薯
浏览 45回答 1
1回答

月关宝盒

要创建任意 ND 网格,meshgrid只需传递更多列表即可。例如,这将创建一个坐标为 1-3 的 9 维网格>>> 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python