如何在xarray中启用季节选择作为JJAS而不是JJA

问题描述

我对 Python 和编程比较陌生,一直在尝试为印度次大陆制作一些初始的降水数据图,专门针对 6 月、7 月、8 月和 9 月期间的印度夏季风。我设法理解了教程中的一些代码以获得如下所示的 JJA 情节,但未能适当修改它以将季节显示为 JJAS 而不是 JJA。简单地用 JJAS 代替 JJA 当然会产生错误

关键错误:'JJAS'

我在同一个论坛上看到了一个解决方案,但我无法将其调整到我的代码中。如果我能收到任何有关这方面的建议,我将不胜感激。谢谢!

下面是代码

import xarray as xr
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import cmocean

accesscm2_pr_file = r'C:\Users\uSER\Desktop\dissTrack1\ESGF data files\pr_Amon_CAMS-CSM1-0_historical_r1i1p1f1_gn_185001-201412.nc'
dset = xr.open_dataset(accesscm2_pr_file)

clim = dset['pr'].groupby('time.season').mean('time',keep_attrs=True)

clim.data = clim.data * 86400
clim.attrs['units'] = 'mm/day'

fig = plt.figure(figsize=[12,5])
ax = fig.add_subplot(111,projection=ccrs.PlateCarree(central_longitude=180))
clim.sel(season='JJAS').plot.contourf(ax=ax,levels=np.arange(0,13.5,1.5),extend='max',transform=ccrs.PlateCarree(),cbar_kwargs={'label': clim.units},cmap=cmocean.cm.haline_r)
ax.coastlines()
plt.show()


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self,key,method,tolerance)
   3360             try:
-> 3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

~\anaconda3\lib\site-packages\pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'JJAS'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_16124/3658430410.py in <module>
     15 fig = plt.figure(figsize=[12,5])
     16 ax = fig.add_subplot(111,projection=ccrs.PlateCarree(central_longitude=180))
---> 17 clim.sel(season='JJAS').plot.contourf(ax=ax,18                    levels=np.arange(0,19                    extend='max',~\anaconda3\lib\site-packages\xarray\core\dataarray.py in sel(self,indexers,tolerance,drop,**indexers_kwargs)
   1269         Dimensions without coordinates: points
   1270         """
-> 1271         ds = self._to_temp_dataset().sel(
   1272             indexers=indexers,1273             drop=drop,~\anaconda3\lib\site-packages\xarray\core\dataset.py in sel(self,**indexers_kwargs)
   2363         """
   2364         indexers = either_dict_or_kwargs(indexers,indexers_kwargs,"sel")
-> 2365         pos_indexers,new_indexes = remap_label_indexers(
   2366             self,indexers=indexers,method=method,tolerance=tolerance
   2367         )

~\anaconda3\lib\site-packages\xarray\core\coordinates.py in remap_label_indexers(obj,**indexers_kwargs)
    419     }
    420 
--> 421     pos_indexers,new_indexes = indexing.remap_label_indexers(
    422         obj,v_indexers,tolerance=tolerance
    423     )

~\anaconda3\lib\site-packages\xarray\core\indexing.py in remap_label_indexers(data_obj,tolerance)
    272             coords_dtype = data_obj.coords[dim].dtype
    273             label = maybe_cast_to_coords_dtype(label,coords_dtype)
--> 274             idxr,new_idx = convert_label_indexer(index,label,dim,tolerance)
    275             pos_indexers[dim] = idxr
    276             if new_idx is not None:

~\anaconda3\lib\site-packages\xarray\core\indexing.py in convert_label_indexer(index,index_name,tolerance)
    189                 indexer = index.get_loc(label_value)
    190             else:
--> 191                 indexer = index.get_loc(label_value,tolerance=tolerance)
    192         elif label.dtype.kind == "b":
    193             indexer = label

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self,tolerance)
   3361                 return self._engine.get_loc(casted_key)
   3362             except KeyError as err:
-> 3363                 raise KeyError(key) from err
   3364 
   3365         if is_scalar(key) and isna(key) and not self.hasnans:

KeyError: 'JJAS'

解决方法

实际上,按 "time.season" 分组只会将您的数据拆分为 "DJF""MAM""JJA""SON"。对于其他月份组合,您需要定义自己的掩码以在取平均值时应用。对于 "JJAS",我经常使用这样的方法:

jjas = dset.time.dt.month.isin(range(6,10))
clim = dset.sel(time=jjas).mean("time")