![](/img/trans.png)
[英]How to map corresponding values of a 2D NumPy array into an 1D array
[英]How to map a 2D numpy array onto a 1D array with another 2D array as a map?
所以,我有两个2D numpy的阵列, data
包含实际样本数据:
[[12 15 5 0]
[ 3 11 3 7]
[ 9 3 5 2]
[ 4 7 6 8]]
另一个location
,包含一个地图,另一个唯一的,非重叠的int值的二维数组,对应于与这两个相同大小的新1D数组中的空格:
[[ 5 6 9 10]
[ 4 7 8 11]
[ 3 2 13 12]
[ 0 1 14 15]]
到目前为止,我能够运行传输的唯一方法是使用简单的for循环:
arr = np.zeros(4*4, dtype = int)
for i in range(4):
for j in range(4):
mapval = location[i, j]
arr[mapval] = data[i, j]
哪个输出正确[ 4 7 3 9 3 12 15 11 3 5 0 7 2 5 6 8]
这对于简单的4 * 4阵列来说很好,但实际的数据集时钟为512 * 512,这种方法需要相当长的时间才能完成。 所以我的问题是,是否有任何函数或方法利用ufuncs / numpy的快速处理功能来更有效地完成这项工作?
您需要对location数组进行排序以对数据数组进行重新排序的索引,可以使用argsort
进行计算:
data.ravel()[location.ravel().argsort()]
# array([ 4, 7, 3, 9, 3, 12, 15, 11, 3, 5, 0, 7, 2, 5, 6, 8])
import numpy as np
data = np.array([[12, 15, 5, 0],
[ 3, 11, 3, 7],
[ 9, 3, 5, 2],
[ 4, 7, 6, 8]])
location = np.array([[ 5, 6, 9, 10],
[ 4, 7, 8, 11],
[ 3, 2, 13, 12],
[ 0, 1, 14, 15]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.