Search code examples
pythonpython-xarray

About changing longitude array from 0 - 360 to -180 to 180 with Python xarray


I am a matlab user trying to use Python more for my computations recently. I am using xarray and would like to change my longitude array from 0 - 360 to -180 to 180 of a geophysical field. But when I do that:

df=xr.open_dataset(ecmwf_winds.nc)
u10=df['u10']
lon=df['longitude']
lon = np.where(lon > 180, lon-360, lon)
[X,Y]=np.meshgrid(lon,df.latitude)
plt.contourf(X,Y,u10)

the contourplot turns out to messy with gaps, which does not make sense. Can anyone please help me with it. I am not sure where I am doing wrong.


Solution

  • You need to assign the values as you've done and then also sort the resulting DataArray along the new coordinate values:

    lon_name = 'longitude'  # whatever name is in the data
    
    # Adjust lon values to make sure they are within (-180, 180)
    ds['_longitude_adjusted'] = xr.where(
        ds[lon_name] > 180,
        ds[lon_name] - 360,
        ds[lon_name])
    
    # reassign the new coords to as the main lon coords
    # and sort DataArray using new coordinate values
    ds = (
        ds
        .swap_dims({lon_name: '_longitude_adjusted'})
        .sel(**{'_longitude_adjusted': sorted(ds._longitude_adjusted)})
        .drop(lon_name))
    
    ds = ds.rename({'_longitude_adjusted': lon_name})