如何将三个列表x,y,z转换为矩阵z [x,y]?

时间:2017-03-21 10:01:55

标签: python numpy

给出三个相同大小的列表public int indexOf(String str, int fromIndex)

k >= fromIndex  && this.startsWith(str, k)

具有x,y,z个浮点值的唯一但不完整的配对,如何将x = [1, 0,.2,.2, 1, 0] y = [0, 0, 0, 1,.2,.2] z = [0, 2, 3, 1, 0, 1] 映射到矩阵x,y,其中z对应于Z[i,j]的{​​{1}} {1}}分别?在示例中,这将类似于

i,j

其中np.unique也可能是x,y。这听起来像是反Z = [[ 2, 0, 3], ['', '', 1], [ 1, 0, '']] ,我可以破解我自己的实现,但是没有预先存在的解决方案吗?

我尝试了建议here,但他们假设一个完整的网格。 Another solution听起来不错,但插入缺失的点,这不是我想要的。

2 个答案:

答案 0 :(得分:4)

一种方法是 -

m,n = np.max(x)+1, np.max(y)+1    
out = np.full((m,n), np.nan)
out[x,y] = z

示例运行 -

In [213]: x = [4,0,2,2,1,0]
     ...: y = [0,0,0,1,2,5]
     ...: z = [0,2,3,1,0,1]
     ...: 

In [214]: m,n = np.max(x)+1, np.max(y)+1    
     ...: out = np.full((m,n), np.nan)
     ...: out[x,y] = z
     ...: 

In [215]: out
Out[215]: 
array([[  2.,  nan,  nan,  nan,  nan,   1.],
       [ nan,  nan,   0.,  nan,  nan,  nan],
       [  3.,   1.,  nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan,  nan,  nan],
       [  0.,  nan,  nan,  nan,  nan,  nan]])

对于浮点值,我们可以使用np.unique(..return_inverse)给出每个X和Y的唯一int ID,它们可以用作行和列索引,用于索引输出数组 -

x_arr = np.unique(x, return_inverse=1)[1]
y_arr = np.unique(y, return_inverse=1)[1]

m,n = np.max(x_arr)+1, np.max(y_arr)+1    
out = np.full((m,n), np.nan)
out[x_arr,y_arr] = z

示例运行 -

In [259]: x = [1, 0,.2,.2, 1, 0]
     ...: y = [0, 0, 0, 1,.2,.2]
     ...: z = [0, 2, 3, 1, 0, 1]
     ...: 

In [260]: x_arr = np.unique(x, return_inverse=1)[1]
     ...: y_arr = np.unique(y, return_inverse=1)[1]
     ...: 
     ...: m,n = np.max(x_arr)+1, np.max(y_arr)+1    
     ...: out = np.full((m,n), np.nan)
     ...: out[x_arr,y_arr] = z
     ...: 

In [261]: out
Out[261]: 
array([[  2.,   1.,  nan],
       [  3.,  nan,   1.],
       [  0.,   0.,  nan]])

答案 1 :(得分:1)

基于Divakar's answer,但也适用于非索引x,y

ux, xi = np.unique(x, return_inverse=1)
uy, yi = np.unique(y, return_inverse=1)
X, Y = np.meshgrid(ux, uy)
Z = np.full(X.shape, np.nan)
Z[xi, yi] = z