我有一個填充了值的 numpy 二維陣列(50x50)。我想將二維陣列展平為一列 (2500x1),但這些值的位置非常重要。索引可以轉換為空間坐標,所以我想要另外兩個 (x,y) (2500x1) 陣列,以便我可以檢索相應值的 x,y 空間坐標。
例如:
My 2D array:
--------x-------
[[0.5 0.1 0. 0.] |
[0. 0. 0.2 0.8] y
[0. 0. 0. 0. ]] |
My desired output:
#Values
[[0.5]
[0.1]
[0. ]
[0. ]
[0. ]
[0. ]
[0. ]
[0.2]
...],
#Corresponding x index, where I will retrieve the x spatial coordinate from
[[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
...],
#Corresponding y index, where I will retrieve the x spatial coordinate from
[[0]
[0]
[0]
[0]
[1]
[1]
[1]
[1]
...],
關于如何做到這一點的任何線索?我已經嘗試了一些東西,但它們沒有奏效。
uj5u.com熱心網友回復:
為了簡單起見,讓我們用這段代碼重現你的陣列:
value = np.arange(6).reshape(2, 3)
首先,我們創建變數 x, y ,其中包含每個維度的索引:
x = np.arange(value.shape[0])
y = np.arange(value.shape[1])
np.meshgrid 是與您描述的問題相關的方法:
xx, yy = np.meshgrid(x, y, sparse=False)
最后,使用以下幾行將所有元素轉換為您想要的形狀:
xx = xx.reshape(-1, 1)
yy = yy.reshape(-1, 1)
value = value.reshape(-1, 1)
uj5u.com熱心網友回復:
根據您的示例,使用np.indices:
data = np.arange(2500).reshape(50, 50)
y_indices, x_indices = np.indices(data.shape)
重塑您的資料:
data = data.reshape(-1,1)
x_indices = x_indices.reshape(-1,1)
y_indices = y_indices.reshape(-1,1)
uj5u.com熱心網友回復:
假設您想展平并重塑為單列,請使用reshape:
a = np.array([[0.5, 0.1, 0., 0.],
[0., 0., 0.2, 0.8],
[0., 0., 0., 0. ]])
a.reshape((-1, 1)) # 1 column, as many row as necessary (-1)
輸出:
array([[0.5],
[0.1],
[0. ],
[0. ],
[0. ],
[0. ],
[0.2],
[0.8],
[0. ],
[0. ],
[0. ],
[0. ]])
獲取坐標
y,x = a.shape
np.tile(np.arange(x), y)
# array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])
np.repeat(np.arange(y), x)
# array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2])
或簡單地使用unravel_index:
Y, X = np.unravel_index(range(a.size), a.shape)
# (array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]),
# array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/387128.html
上一篇:無論如何優化一個大(127K)閱讀英文單詞txt檔案
下一篇:如何使用過濾值從舊物件創建新物件
