在Python中将2D网格转换为3D数组



我在网格中有坐标(纬度,经度),以及与每个"点"相关的数据。我想导出到。csv,并有每个点与我想分析的数据相关联。到目前为止,我的代码看起来像这样:

xx1,yy1=np.meshgrid(xx,yy)
row_format = np.stack([z.ravel() for z in (xx1, yy1, data['Hs'])], axis=1)
print(row_format)
pd.DataFrame(row_format).to_csv('sample.csv')

数据在一个有一定顺序的数据框架中。但是输出如下所示:

<表类>xyhtbody><<tr>265190266191267192

假设您的数据框架名为df,您可以执行以下操作。一些笔记:

  • y_cycle目前从19到1(总共19个值)。如果您想在y循环回到开始之前总共有20个值,则将np.arange语句中的0更改为-1。
  • 最后2行替换当前df中的xy列。如果您希望新的xy值(存储在repeated_xrepeated_y中)成为新列,您可以将df["x"]更改为不同的列名,df["y"]也是如此。
y_cycle = np.arange(19, 0, -1)
length_y_cycle = len(y_cycle)
x_start = 265
length = len(df)
num_y_cycles = int(math.ceil(length / length_y_cycle))
repeated_y = np.tile(y_cycle.reshape(1, length_y_cycle), num_y_cycles)[0][:length]
x_fin = x_start + num_y_cycles - 1
repeated_x = np.repeat(np.arange(x_start, x_fin+1, 1), length_y_cycle)[:length]
df["x"] = repeated_x
df["y"] = repeated_y

如果你有任何问题请告诉我。

最新更新