Numpy:将xyzV表格转换为网格

b4qexyjb  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(119)

我有一个文本文件,我可以用numpy.loadtxt读取到一个2D数组中:

X   Y   Z   V
-30 -15 -25  2
-29 -15 -25  2.1
-28 -15 -25  2.2
 .   .   .    .
 .   .   .    .
+29 -15 -25  2.1
+30 -15 -25 -2.0
-30 -14 -25  2   # now iterating X values while Y=-14
-29 -14 -25  2.1
-28  .   .   2.2
 .   .   .    .
 .   .   .    .
+29 -13 -25  2.1
+30 -13 -25 -2.0 # now iterating X values while Y=-13, and so on...
 .   .   .    .
 .   .   .    .
 .   .   .    .
 .   .   .    .

X、Y和Z的范围不一定是整数,并且如上所述,在所有轴上不相同。我想用这些数据创建一个网格,即得到数组,使得:

>>> np.shape(V)
(61,31,51)
>>> np.shape(x)
(61,)
>>> np.shape(y)
(31,)
>>> np.shape(z)
(51,)

我看到了一个几乎identical question here,但很明显,那里的答案依赖于这样一个事实,即XY列包含从已知正数开始的整数。

svmlkihl

svmlkihl1#

假设该表与X,Y和Z值的重复一致,您可以使用np.uniquelen来计算结果数组应获得的形状。下面是一段完整的代码:

import numpy as np

table = np.loadtxt("potential.csv", delimeter=",", skiprows=1)
x = np.unique(table[:,0])
y = np.unique(table[:,1])
z = np.unique(table[:,2])

potential = np.zeros((len(x), len(y), len(z)))
for i in range(len(z)):
    for j in range(len(y)):
        for k in range(len(x)):
            index = k + j*len(x)+ i*len(y)*len(x)
            potential[k,j,i] = table[index, 3]

np.reshape不适合这种情况。要在table的一维数组中找到正确的index,必须使用Y值在迭代所有X值后更改的事实。因此,我们将j乘以x的长度。Z索引与X和Y长度的关系也是如此。

相关问题