通过Xarray通过两个坐标指定的尺寸保存NetCDF

如何解决通过Xarray通过两个坐标指定的尺寸保存NetCDF

我在大熊猫中有地理信息。我有一个功能,可以通过以下方式通过xarray将该信息保存到netcdf

def write_ncfile(name,new_model,variables):
    ## Distinct latitudes
    lats=new_model.drop_duplicates(["ilat"],keep="first").geometry.y.values
    ## Distinct Longitudes
    lons=new_model.drop_duplicates(["ilon"],keep="first").geometry.x.values

    ## Temporal store for DataArrays
    temporal_dataset = {}

    ## Dimensions and coordinates
    dims = ('lat','lon')
    coords = dict(lat=lats,lon=lons)

    ## Variables to save
    for variable in variables:
        bcvar=new_model[variable].values
        ## Reshapes data to have sahpe of lats and lons
        bcvar=np.reshape(bcvar,(-1,len(lons)))
        ds = xr.DataArray(bcvar,dims=dims,coords=coords)
        ds.attrs['long_name'] = descriptions[variable] 
        ds.attrs['_FillValue'] = 0
        temporal_dataset[variable] = ds
    ## Create DataSet
    DT=xr.Dataset(temporal_dataset)

    ## Save to file
    makedirs(name,exist_ok = True)
    filename="%s/%s.nc"%(name,name)
    DT.to_netcdf(filename,format="NETCDF4_CLASSIC")

    return None

如果底层地理网格是正方形的(经纬度投影),那么此代码将发挥出色的作用,但是现在如果投影的位置不是正方形(ex lambert),则需要将尺寸定义为2d数组而不是1d。我对如何做到这一点感到困惑。

我正在尝试在ncdump的标题中实现类似的目的

dimensions:
lat:dim_lat
lon:dim_lon
variables:
double lat(lat,lon)
double lon(lat,lon)
double var1(lat,lon)
double var2(lat,lon)

当前代码将其另存为

dimensions:
lat:dim_lat
lon:dim_lon
variables:
double lat(lat)
double lon(lon)
double var1(lat,lon)

我该如何更改?


示例gdf:

     ilat  ilon                   geometry            d_p         T_P          d_v         T_V              
22     0     0  POINT (-70.95000 -33.30000)      0.000000           0     0.000000           0              
0      0     1  POINT (-70.85000 -33.30000)    383.862700       39674   120.439438       12448              
1      0     2  POINT (-70.75000 -33.30000)    327.639330       33863   112.502638       11628              
2      0     3  POINT (-70.65000 -33.30000)    320.808104       33157    96.602750        9984              
3      0     4  POINT (-70.55000 -33.30000)    415.217240       42915    99.144774       10247              
23     1     0  POINT (-70.95000 -33.40000)      0.000000           0     0.000000           0              
4      1     1  POINT (-70.85000 -33.40000)     56.055971        5787    16.853605       17310              
5      1     2  POINT (-70.75000 -33.40000)   6686.807845      690341  1992.373592      205691            
6      1     3  POINT (-70.65000 -33.40000)   8812.040534      909749  3512.456618      362623              
7      1     4  POINT (-70.55000 -33.40000)   5203.112762      537166  2015.376536      208066              
24     2     0  POINT (-70.95000 -33.50000)      0.000000           0     0.000000           0              
8      2     1  POINT (-70.85000 -33.50000)    133.485233       13765    40.937021        4222              
9      2     2  POINT (-70.75000 -33.50000)   7358.668562      758846  2309.069300      238118              
10     2     3  POINT (-70.65000 -33.50000)  10420.377036     1074578  3668.947758      378352              
11     2     4  POINT (-70.55000 -33.50000)   6166.780423      635935  2047.500621      211144              
12     3     0  POINT (-70.95000 -33.60000)     71.933395       74010    21.287101        2193              
13     3     1  POINT (-70.85000 -33.60000)   1154.803477      118952   373.474444       38470              
14     3     2  POINT (-70.75000 -33.60000)   1512.189352      155764   466.310819       48033              
15     3     3  POINT (-70.65000 -33.60000)   7160.093545      737532  2095.296251      215828              
16     3     4  POINT (-70.55000 -33.60000)   4870.217943      501661  1494.220152      153914              
17     4     0  POINT (-70.95000 -33.70000)    767.033734       78919   241.884877       24887              
18     4     1  POINT (-70.85000 -33.70000)    163.023696       16773    48.526857        4993              
19     4     2  POINT (-70.75000 -33.70000)    632.011798       65027   207.326845       21332              
20     4     3  POINT (-70.65000 -33.70000)     93.053338        9574    27.787137        2859

函数用法为

write_ncfile("Trial",gdf,["d_p","d_v"])

在上面的示例中,信息保存与上面的代码完全一样,但是我需要对其进行概括,以便在网格不是正方形网格的情况下也能正常工作。

解决方法

我遇到了同样的问题,并且xarray在这一点上不是很直观。创建尺寸正确的DataArray的解决方案(请注意,这是3D示例):

    data_array = xarray.DataArray(
        data,coords={
            "time": timestamps,"latitude": (["y","x"],latitude_grid),"longitude": (["y",longitude_grid),},dims=["time","y",)

因此,代码中的循环应如下所示:

    coords = {
            "latitude": (["lon","lat"],"longitude": (["lon",longitude_grid)}
    dims = ['lon','lat']
    for variable in variables:
        bcvar=new_model[variable].values
        ## Reshapes data to have sahpe of lats and lons
        bcvar=np.reshape(bcvar,(-1,len(lons)))
        ds = xr.DataArray(bcvar,dims=dims,coords=coords)
        ds.attrs['long_name'] = descriptions[variable] 
        ds.attrs['_FillValue'] = 0
        temporal_dataset[variable] = ds

请随时根据您的最终运行解决方案进行调整。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-