xarray使用与另一个fi相同的lat/lon网格创建新数据集

2024-04-29 03:52:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个陆地表面模型,我想用一些虚拟数据来测试。有一个数据集读取时没有错误。土壤数据如下:

<xarray.dataset>
Dimensions:    (time: 1, x: 200, y: 200)
Coordinates:
  * time       (time) float64 1.051e+04
Dimensions without coordinates: x, y
Data variables:
    t_clay     (time, y, x) float32 ...
    t_sand     (time, y, x) float32 ...
    t_silt     (time, y, x) float32 ...
    t_sum      (time, y, x) float32 ...
    s_clay     (time, y, x) float32 ...
    s_sand     (time, y, x) float32 ...
    s_silt     (time, y, x) float32 ...
    s_sum      (time, y, x) float32 ...
    latitude   (y, x) float64 40.0 40.0 40.0 40.0 40.0 ... 50.0 50.0 50.0 50.0
    longitude  (y, x) float64 0.0 0.0656 0.1312 0.1968 ... 15.4 15.48 15.56
Attributes:
    Conventions:     CF-1.0
    content:         HARMONIZED WORLD SOIL DATABASE; first it was aggregated ...
    scaling_factor:  20

我想在我的其他变量中使用相同的latitude/longitude网格。在

例如,辐射数据(随机生成的值)如下所示:

^{pr2}$

1。我需要创建一个新的xr.Dataset形状与上面的土壤数据相同。

2。我还需要将longitude&;latitudeCoordinates存储为Data variables

当Fortran存储为Coordinate而不是Variable时,它在读取“经度”时遇到了问题

谢谢!在


Tags: 数据datatimevariablesdimensionssum土壤float64
1条回答
网友
1楼 · 发布于 2024-04-29 03:52:20

因此,我使用以下代码成功地从另一个xr.Dataset对象中的数据制作了样本:

1。导入包

import numpy as np
import xarray as xr
from shutil import copyfile
import os

np.random.seed(123)

2。根据土壤数据初始化“骨架”

^{pr2}$

3。循环每个变量,从感兴趣的变量(Rg)中随机抽取值,并插入到旧的xr.Dataset提供的骨架中。

for var in l:
    filename = data_dir + "{}_dummy.nc".format(var)
    print("** Creating file: ", filename, " **")

    # copy file and open the new temp file
    copyfile(filename, data_dir + "temp.nc")
    ds = xr.open_dataset(data_dir + "temp.nc")

    # generate randomly from variable in another xarray object
    s.s_sum.values = np.random.choice(
        ds[var].values.flatten(), size=s.s_sum.values.shape
    )
    ds = s.copy()
    ds = ds.rename({"s_sum": var})

    ds.to_netcdf(filename, format="NETCDF3_CLASSIC")
    print("File Created!")

    # remove temporary file
    os.remove(data_dir + "temp.nc")
    print("Temporary Data Removed")

    del ds

我认为这个程序对于其他需要为水文和气候模型生成随机强迫数据的人来说是非常有用的。在

相关问题 更多 >