2

I'm experiencing an error that I cannot seem to resolve when attempting to convert from a Dataset to array when using xarray. I'm encountering this because I'm attempting to add a time dimension to a netcdf file (open netcdf, add a timestamp that is the same across all data, save out netcdf).

import xarray as xr
import pandas as pd

scriptpath = os.path.dirname(os.path.abspath(__file__))

outputfile = scriptpath + '\\20210629_deadgrass.aus.nc'

times= pd.to_datetime(str(yesterday.strftime('%Y%m%d')))
time_da = xr.Dataset({"time": times})

arr = xr.open_dataset(outputfile)
ds = arr.to_array()
dst = ds.expand_dims(time=time_da) #errors here

The error I'm receiving is

Exception has occurred: TypeError
cannot directly convert an xarray.Dataset into a numpy array. Instead, create an xarray.DataArray first, either with indexing on the Dataset or by invoking the `to_array()` method.
  File "Z:\UpdateAussieGRASS.py", line 101, in <module>
    dst = ds.expand_dims(time=time_da)

I can't seem to work out what I'm doing wrong with to_array() in the second last line. Examples of to_array() are here. Autogenerated documentation is here.

1 Answer 1

3

ds is already an xarray.DataArray. The error occurs on this line:

dst = ds.expand_dims(time=time_da) #errors here

Because while ds is a DataArray, time_da is not. This should work:

dst = ds.expand_dims(time=time_da.to_array())
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. So, I've moved on to a different problem with that line using your modification. Exception has occurred: ValueError at least one array or dtype is required File "Z:\UpdateAussieGRASS.py", line 104, in <module> dst = ds.expand_dims(time=time_da.to_array()). Shouldn't an array be present since we just did a to_array?
@anakaine, is that still an error ? @Kraigolas, is there doc on what to_array actually does / how it works / pitfalls (a soft question) ? Thanks

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.