亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號