为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只萌萌小番薯 2023-12-05 15:29:00
其想法是创建可被 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 excelrep_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 excelTable_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 excelt3_1 = np.tile(sorted_array,(64,1))Table_9d=np.concatenate((T3 , t3_1 ), axis=1) 最终,我希望有一个千量级的更高维度坐标。虽然可以扩展上面的代码,但我不确定如何概括它来处理更高的维度要求。感谢任何想法或阅读材料。ps,创建这么大维度的主要原因是因为我想应用 Pandas Vectorization。
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

要创建任意 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)


查看完整回答
反对 回复 2023-12-05
  • 1 回答
  • 0 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信