如何在更改尺寸的情况下使用xr.apply_ufunc [英] How to use xr.apply_ufunc with changing dimensions

查看:260
本文介绍了如何在更改尺寸的情况下使用xr.apply_ufunc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个气候数据集,其中3个维度都装有xarray

I have a climate dataset with 3 dimensions loaded with xarray

climate = xr.open_dataset(data_file)
climate
<xarray.Dataset>
Dimensions:  (lat: 621, lon: 1405, time: 424)
Coordinates:
  * time     (time) datetime64[ns] 2017-11-01 2017-11-02 2017-11-03 ...
  * lon      (lon) float64 -125.0 -125.0 -124.9 -124.9 -124.8 -124.8 -124.7 ...
  * lat      (lat) float64 49.92 49.87 49.83 49.79 49.75 49.71 49.67 49.62 ...
Data variables:
  tmean    (time, lat, lon) float64 nan nan nan nan nan nan nan nan nan ...
  status   (time) object 'provisional' 'provisional' 'provisional' ...

我有一个模型,该模型适用于时间维度,并返回仅包含纬度和经度的2d数组.

I have a model which gets applied to the time dimension, and returns a 2d array of just the lat,lon.

apply_model(climate.tmean.values).shape
(621, 1405)

如何在xr.apply_ufunc()中使用它?我尝试了几种不同的方法,但是它总是抱怨某些尺寸错误.

How can I use this within xr.apply_ufunc()? I've tried several different things but it always complains of some dimension error.

例如:

def apply_model_ufunc(climate):
    return xr.apply_ufunc(
            apply_model, climate,
            input_core_dims=[['lat','lon']])

apply_model_ufunc(climate)
ValueError: dimensions ('time',) must have the same length as the number of data dimensions, ndim=2

def apply_model_ufunc(climate):
    return xr.apply_ufunc(
            apply_model, climate,
            input_core_dims=[['time','lat','lon']],
            output_core_dims=[['lat','lon']])

apply_model_ufunc(climate)
ValueError: operand to apply_ufunc has required core dimensions ['time', 'lat', 'lon'], but some of these are missing on the input variable:  ['lat', 'lon']

推荐答案

经过一番摆弄之后,我想我已经明白了.问题是apply_ufunc会将函数应用于所有数据变量.我的数据集中的状态"变量引起问题,因为它只有时间维度.工作代码为

After some more fiddling I think I figured out out. The issue was apply_ufunc will apply the function over all data variables. The "status" variable in my dataset was causing issues as it only has the time dimension. The working code was

def apply_model_ufunc(climate):
    return xr.apply_ufunc(
            apply_model, climate,
            input_core_dims=[['time']],
            output_dtypes=[float])

apply_model_ufunc(climate['tmean'])

这篇关于如何在更改尺寸的情况下使用xr.apply_ufunc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆