我在这里是一个“自包含”的答案,因为我首先生成一些输入数据,然后将其转换为字典,然后再转换回原始数组。在途中,我添加了一些随机噪声以保持 x 和 y 值彼此接近,但仍使它们独一无二。在this answer 之后,可以通过首先对值进行四舍五入然后使用np.unique 来找到所有彼此“接近”的值的列表。
mport numpy as np
##generating some input data:
print('input arrays')
xvals = np.linspace(1,10, 5)
print(xvals)
yvals = np.linspace(0.1, 0.4, 4)
print(yvals)
xvals, yvals = np.meshgrid(xvals, yvals)
##adding some noise to make it more interesting:
xvals += np.random.rand(*xvals.shape)*1e-3
yvals += np.random.rand(*yvals.shape)*1e-5
zvals = np.arange(xvals.size).reshape(*xvals.shape)
print(zvals)
input_dict ={
(i,j): k for i,j,k in zip(
list(xvals.flatten()), list(yvals.flatten()), list(zvals.flatten())
)
}
##print(input_dict)
x,y,z = map(np.array,zip(*((x,y,z) for (x,y),z in input_dict.items())))
##this part will need some tweaking depending on the size of your
##x and y values
xlen = len(np.unique(x.round(decimals=2)))
ylen = len(np.unique(y.round(decimals=3)))
x = x.round(decimals=2).reshape(ylen,xlen)[0,:]
y = y.round(decimals=3).reshape(ylen,xlen)[:,0]
z = z.reshape(ylen,xlen)
print('\n', 'output arrays')
print(x)
print(y)
print(z)
输出如下:
input arrays
[ 1. 3.25 5.5 7.75 10. ]
[0.1 0.2 0.3 0.4]
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
output arrays
[ 1. 3.25 5.5 7.75 10. ]
[0.1 0.2 0.3 0.4]
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
旧答案:
这个答案有很多假设,主要是因为问题中没有足够的信息。但是,假设
- x 和 y 值的顺序与示例数据中的一样好
- x 和 y 值是完整的
人们可以通过列表理解和重塑 numpy ndarrays 来解决这个问题:
import numpy as np
input_dict = {
(0,0): 1,
(1,0): 2,
(0,1): 3,
(1,1): 4,
}
x,y,z = map(np.array,zip(*((x,y,z) for (x,y),z in input_dict.items())))
xlen = len(set(x))
ylen = len(set(y))
x = x.reshape(xlen,ylen)[0,:]
y = y.reshape(xlen,ylen)[:,0]
z = z.reshape(xlen,ylen)
print(x)
print(y)
print(z)
给了
[0 1]
[0 1]
[[1 2]
[3 4]]
希望这会有所帮助。
PS:如果 x 和 y 值不一定按照发布的示例数据建议的顺序,仍然可以通过一些巧妙的排序来解决问题。