1

I'm using xarray.DataArray for loading data. One of the variables 'mtime' in the data looks like:

xarray.DataArray 'mtime' (mtimedim: 3) 
array([149,  13,   0]) 

Coordinates:     time     datetime64[ns] 2009-05-29T13:00:00     
    lon      float64 -150.0     
    lat      float64 11.25     
    LBC      float64 ... 
Dimensions without coordinates: mtimedim 
Attributes:     long_name:  model times (day, hour, minute)     
units:      day, hour, minute

I wish to fetch the first element 149 in the DataArray. I would like to fetch it as an individual element and not as xarray. I'm currently doing it as

data.mtime.to_series()[0] 

And my output is 149. Is this the right way to do it or is there a better approach? Appreciate your help. Thanks.

1 Answer 1

2

You can do either

data[0].values  # -> gives 0d-np.array
data[0].values.item()  # -> gives a scalar
data.values[0]  # -> gives a scalar

.values returns a raw np.array. .data returns a np.array or dask.array depending on the backend.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply. When data contains only one element, I get the error - IndexError: too many indices for array when I try data.values[0] and data[0].values. I don't quite understand the error message. For me, it looks like there is more data and I'm not using the right number of indices to access the data. Can you please clarify why I get this message and what it means?
I think your data is 0d-array. What will happen if you do data.values.item()?
You are right. Data is 0d-array. <xarray.DataArray 'Z' ()> array(50476781.92) Coordinates: time datetime64[ns] 2009-05-29T02:00:00 LBC float64 -7.0 lat int32 10 ilev float64 6.89 lon int32 78 Attributes: long_name: GEOPOTENTIAL HEIGHT units: cm data[0].values #--> IndexError: too many indices data[0].values.item() #--> IndexError: too many indices data.values[0] #--> IndexError: too many indices for array data.values #--> array(50476781.92) (array) data.values.item() #--> 50476781.92 (scalar)
Sorry for the bad formatting. I'm new to stackoverflow and trying to understand how to make the code look good. I still don't understand the error message 'Too many indices' or is it actually 'too less indices'?
noting that xarray now includes da.item() for 0-D DataArrays, so the example here for retrieving a scalar could simply be data[0].item()

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.