简体   繁体   English

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

[英]How to convert three lists x,y,z into a matrix z[x,y]?

Given three lists x,y,z of identical size à la 给定三个相同大小的列表x,y,z

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

with unique but incomplete pairings of x,y float values, how to map z to a matrix Z[i,j] where i,j correspond to the indices np.unique of x,y respectively? 具有唯一但不完整的x,y浮点值对,如何将z映射到矩阵Z[i,j] ,其中i,j对应于x,y的索引np.unique In the example this would be something like 在示例中,这类似于

Z = [[ 2,  0,  3],
     ['', '',  1],
     [ 1,  0, '']]

where '' might as well be np.nan . 其中''最好是np.nan This does somehow sound like an inverse np.meshgrid , and I could hack up my own implementation, but is there no pre-existing solution? 这听起来像是一个反向np.meshgrid ,我可以破解自己的实现,但是没有预先存在的解决方案吗?

I tried the suggestions here , but they assume a complete grid. 我在这里尝试了这些建议,但它们假定使用完整的网格。 Another solution sounds nice but interpolates the missing points, which is not what I want. 另一个解决方案听起来不错,但可以插补缺失的点,这不是我想要的。

One approach would be - 一种方法是-

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

Sample run - 样品运行-

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]])

For floating point values, we could use np.unique(..return_inverse) to give each of the X's and Y's unique int IDs, which could be used as row and column indices for indexing into output array - 对于浮点值,我们可以使用np.unique(..return_inverse)给出X和Y的每个唯一的int ID,这些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

Sample run - 样品运行-

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]])

Based on Divakar's answer , but also working for non-index x,y s: 基于Divakar的答案 ,但也适用于非索引x,y s:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM