Sum Data variables of Dataset

Viewed 182

I've merged a list of DataArray in one DataSet using the code below:

    surface_dataarray = []

    for (key, value) in surfaces_item_service.items():
        print(f'{key}: {value}')
        single_surface_class = __yearly_surface_type(folder_path, provider, data_source, bins, key)
        single_surface_class.name = key
        if single_surface_class.count() > 1:
            single_surface_class.rio.to_raster(output_file_path + f'/{key}.tif', driver="GTiff")
            surface_dataarray.append(single_surface_class)

    surface_data = xr.merge(surface_dataarray)

And I have obtained a Dataset like the below:

<xarray.Dataset>
Dimensions:            (x: 1868, y: 1373)
Coordinates:
    band               int64 1
  * x                  (x) float64 4.269e+05 4.269e+05 ... 4.455e+05 4.455e+05
  * y                  (y) float64 4.53e+06 4.53e+06 ... 4.516e+06 4.516e+06
    spatial_ref        int64 0
    year               int64 2020
    variable           <U15 'CLASSIFIED DATA'
Data variables:
    water_surface      (y, x) float32 nan nan nan nan nan ... nan nan nan nan
    non_green_surface  (y, x) float32 nan nan nan nan nan ... nan nan nan nan
    green_surface      (y, x) float32 nan nan nan nan nan ... nan nan nan nan

Is it possible to sum the Data variables? I need to save as single band. NB: there are nan values because my area doesn't have values at borders.

1 Answers

Yes, one way to do it is to use Dataset.to_array, which will combine all the data variables into a single array along a new "variable" dimension:

sum_of_data_variables = ds.to_array().sum("variable")
Related