About changing longitude array from 0 - 360 to -18

2020-07-25 09:48发布

问题:

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.

回答1:

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})


回答2:

Another faster approach and much simpler approach without using where would be

 df.coords['lon'] = (df.coords['lon'] + 180) % 360 - 180
 df = df.sortby(df.lon)

Tip: For quick plotting, you can use Xarrays inbuilt plotting function so you won't have to create a meshgrid.

df.u10.plot()
#or
df.u10.plt.contourf()