关于使用 Python xarray 将经度数组从 0 - 360 更改为 -180 到 180
About changing longitude array from 0 - 360 to -180 to 180 with Python xarray
我是一名 matlab 用户,最近尝试使用 Python 进行更多计算。我正在使用 xarray 并想将地球物理场的经度数组从 0 - 360 更改为 -180 到 180。但是当我这样做时:
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)
contourplot 原来是乱七八糟的间隙,这没有意义。谁能帮我解决这个问题。我不确定我哪里做错了。
您需要按照您所做的那样分配值,然后还需要根据新的坐标值对生成的 DataArray 进行排序:
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})
不使用 where
的另一种更快且更简单的方法是
df.coords['lon'] = (df.coords['lon'] + 180) % 360 - 180
df = df.sortby(df.lon)
提示:为了快速绘图,您可以使用 Xarrays 内置的绘图功能,这样您就不必创建网格。
df.u10.plot()
#or
df.u10.plt.contourf()
我是一名 matlab 用户,最近尝试使用 Python 进行更多计算。我正在使用 xarray 并想将地球物理场的经度数组从 0 - 360 更改为 -180 到 180。但是当我这样做时:
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)
contourplot 原来是乱七八糟的间隙,这没有意义。谁能帮我解决这个问题。我不确定我哪里做错了。
您需要按照您所做的那样分配值,然后还需要根据新的坐标值对生成的 DataArray 进行排序:
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})
不使用 where
的另一种更快且更简单的方法是
df.coords['lon'] = (df.coords['lon'] + 180) % 360 - 180
df = df.sortby(df.lon)
提示:为了快速绘图,您可以使用 Xarrays 内置的绘图功能,这样您就不必创建网格。
df.u10.plot()
#or
df.u10.plt.contourf()