I'm struggling to calculate the trend of a variable through time. I have a variable CESMnofert_latavg
:
ScreenShot_CESMnofert_latavg.png
The problem seems to be with cftime
I've tried two approaches:
CESMnofert_NBPtrend = stats.linregress(CESMnofert_latavg.time, CESMnofert_latavg) z = np.polyfit(CESMnofert_latavg.time, CESMnofert_latavg, 1)
Both result in error messages stating:
TypeError: unsupported operand type(s) for +: 'cftime._cftime.DatetimeNoLeap' and 'float'
Is there a way I should change the time dimension? Or is there something else I need to consider? I ultimately want to create a latitudinal plot that shows the temporal trend at each latitude.
It looks like you're regressing against the time dimension, which is represented as a cftime._cftime.DatetimeNoLeap
object. If you're happy with treating time steps as integer indexes, you should be able to use time dimension integer indexes, though I'm not sure of the syntax offhand.
Try Dataset.polyfit
or DataArray.polyfit
I think it does all these manipulations for you. The output units are in ns
though!
If you're loading the data from NetCDF, you could try adding decode_cf=False
to your dataset open statement, and you may have integer indexes instead of time objects.
Thanks! I was able to get something to work using DataArray.polyfit
. @Deepak Cherian , what do you mean by units in ns
?
I'm not sure I fully understand this function so I'll keep playing around with it. I found the docs page for it, but can't seem to find examples of it in use.
See https://github.com/pydata/xarray/issues/4455 the output values are sometimes confusing. I guess I should have written (data units)/nanosecond
I am not sure what happens with cftime though.
Thanks Deepak. The units do seem to be in nanoseconds with cftime as well. I initially asked because the values plotted as 1e-18, so I'm glad to know it's not a mistake on my part.
I went through this same process a few weeks back! @Danica Lombardozzi If you're looking for an example with xr.polyfit
I have one here: https://github.com/katiedagon/GLENS-Ecosystems/blob/main/notebooks/climateVelocity.ipynb (sorry the notebook is kind of long and messy, just search for "polyfit" to find relevant code)
Thanks @Katie Dagon ! It's really nice to have an example of this in action!
Last updated: May 16 2025 at 17:14 UTC