1

I have a NetCDF file which looks like this:

<xarray.Dataset>
Dimensions:    (time: 180, d2: 2, lat: 180, lon: 360)
Coordinates:
  * time       (time) object 2000-01-15 12:00:00 ... 2014-12-15 12:00:00
  * lat        (lat) float64 -89.5 -88.5 -87.5 -86.5 ... 86.5 87.5 88.5 89.5
  * lon        (lon) float64 0.5 1.5 2.5 3.5 4.5 ... 356.5 357.5 358.5 359.5
Dimensions without coordinates: d2
Data variables:
    time_bnds  (time, d2) object ...
    lat_bnds   (lat, d2) float64 ...
    lon_bnds   (lon, d2) float64 ...
    zos        (time, lat, lon) float32 ...
Attributes: (12/45)
    Conventions:            CF-1.7 CMIP-6.2
    activity_id:            CMIP
    case_id:                23
    cesm_casename:          b.e21.BHIST.f09_g17.CMIP6-historical.009
    contact:                [email protected]
    creation_date:          2019-01-27T12:33:42Z
    ...                     ...
    variable_id:            zos
    variant_info:           CMIP6 20th century experiments (1850-2014) with C...
    variant_label:          r9i1p1f1
    branch_time_in_parent:  295650.0
    branch_time_in_child:   674885.0
    branch_method:          standard

I extracted a spatial partition of the data while retaining all the time slices:

lat_bnds, lon_bnds = [25, 50], [-85 + 360, -60 + 360]
lats = DS.variables['lat'][:]
lons = DS.variables['lon'][:]
lat_inds = np.where((lats > lat_bnds[0]) & (lats < lat_bnds[1]))
lon_inds = np.where((lons > lon_bnds[0]) & (lons < lon_bnds[1]))
lat_inds_2 = list(lat_inds[0])
lon_inds_2 = list(lon_inds[0])
DS_subset = DS.variables['zos'][:, lat_inds_2, lon_inds_2]

This extracted data DS_subset looks like this:

<xarray.Variable (time: 180, lat: 25, lon: 25)>
[112500 values with dtype=float32]
Attributes: (12/19)
    cell_measures:  area: areacello
    cell_methods:   area: mean where sea time: mean
    comment:        Model data on the 1x1 grid includes values in all cells f...
    description:    This is the dynamic sea level, so should have zero global...
    frequency:      mon
    id:             zos
    ...             ...
    time_label:     time-mean
    time_title:     Temporal mean
    title:          Sea Surface Height Above Geoid
    type:           real
    units:          m
    variable_id:    zos

Now I am trying to save this extracted data DS_subset as a new netcdf file:

new_filename = './data/newfile.nc'
xr.Dataset(DS_subset.to_xarray()).to_netcdf(path=new_filename)

But I keep getting this error:

AttributeError: 'Variable' object has no attribute 'to_xarray'

What am I doing wrong?

1
  • Why did you use np.where when xarray has .where method? That would make you code easier. Also, DS_subset is a Variable object, so you can run directly DS_subset.to_netcdf(path=new_filename)
    – aldo_tapia
    Apr 17, 2023 at 13:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.