Reputation: 3515
I have a DataArray object named test
. It contains a variable named FFDI 90TH PERCENTILE
and latitude and longitude dimensions.
import numpy as np
import pandas as pd
import xarray as xr
print(test)
<xarray.DataArray 'FFDI 90TH PERCENTILE' (latitude: 106, longitude: 193)>
array([[ 2.699949, 2.699277, 2.677113, ..., 3.353225, 3.381503, 3.392549],
[ 2.7 , 2.704608, 2.70228 , ..., 3.422083, 3.435692, 3.465664],
[ 2.720069, 2.71194 , 2.711843, ..., 3.5 , 3.5 , 3.501185],
...,
[34.863322, 34.825574, 34.694171, ..., 8.599811, 8.50329 , 8.815733],
[34.728609, 35.180146, 35.203714, ..., 8.164053, 8.01015 , 7.94335 ],
[34.654186, 34.865241, 34.987067, ..., 7.814975, 7.644326, 7.925 ]])
Coordinates:
* latitude (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9
* longitude (longitude) float32 140.8 140.84792 140.89584 ... 149.95209 150.0
I have the following times
elements:
times = pd.date_range("1972/12/01","2017/12/01",freq='D',closed='left')
time_da = xr.DataArray(times, [('time', times)])
I would like to add a new dimension and call it time
; and assign times as above to the time
dimension as coordinates. So that the new test
DataArray would look like:
<xarray.DataArray 'FFDI 90TH PERCENTILE' (time: 16436, latitude: 106, longitude: 193)>
I have done the following attempts with assign_coords
and expand_dims
. Neither of them worked.
One:
test_assigned = test.assign_coords({'time': times.values})
TypeError: assign_coords() takes 1 positional argument but 2 were given
Two:
test_assigned = test.assign_coords(time=times.values)
ValueError: cannot add coordinates with new dimensions to a DataArray
Upvotes: 1
Views: 4120
Reputation: 2097
This is a use-case for expand_dims
, which will expand out the array along the new dimension and assign a coordinate to it if provided:
result = test.expand_dims(time=time_da)
Upvotes: 2