其想法是創建可被 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)
添加回答
舉報
0/150
提交
取消