【Python】xarray交换维度、更改变量内部的维度位置教程 | 您所在的位置:网站首页 › python数组维度 › 【Python】xarray交换维度、更改变量内部的维度位置教程 |
目标:修改nc文件中dims中每一维的位置。 首先读取nc文件并查看内部维度分布情况。 #读取nc文件 import xarray as xr a = xr.open_dataset(r'D:/xxx.nc') #查看内部情况 print(a)发现其内部维度分布如下: Dimensions: (lon: 756, lat: 756, time: 263) Coordinates: * lon (lon) float32 64.25 64.35 64.45 64.55 ... 139.6 139.7 139.8 * lat (lat) float32 76.75 76.65 76.55 76.45 ... 1.55 1.45 1.35 1.25 * time (time) datetime64[ns] 1979-02-01 1979-03-01 ... 2000-12-01 Data variables: precipitation (time, lat, lon) float32 ... Attributes: history: Created on xxxx-xx-xx xx:xxDimentions和Coordinates中的经、纬及时间维度和变量所对应的位置是不一致的看着很难受,可以用如下代码修改Dimentions和Coordinates中变量的位置,如下: a1 = a[['time', 'lat', 'lon', 'precipitation']] print(a1)注意除了dims里的变量还要把变量名加进去定位置,否则变量里为空。最后发现其与变量内部排布顺序一致了。 Dimensions: (time: 263, lat: 756, lon: 756) Coordinates: * time (time) datetime64[ns] 1979-02-01 1979-03-01 ... 2000-12-01 * lat (lat) float32 76.75 76.65 76.55 76.45 ... 1.55 1.45 1.35 1.25 * lon (lon) float32 64.25 64.35 64.45 64.55 ... 139.6 139.7 139.8 Data variables: precipitation (time, lat, lon) float32 ... Attributes: history: Created on xxxx-xx-xx xx:xx目标:修改nc文件中变量的维度位置。 当然可根据个人需要修改成自己想要的位置。如果想让原位置不动,更改变量部分的维度位置,使用transpose即可,内部写好目标维度的位置。 a2 = a.transpose('lon','lat','time')这样变量内部维度排布由原来的(time,lat,lon)变成了(lon,lat,time),和Dimentions和Coordinates中的位置一致了。 Dimensions: (lon: 756, lat: 756, time: 263) Coordinates: * lon (lon) float32 64.25 64.35 64.45 64.55 ... 139.6 139.7 139.8 * lat (lat) float32 76.75 76.65 76.55 76.45 ... 1.55 1.45 1.35 1.25 * time (time) datetime64[ns] 1979-02-01 1979-03-01 ... 2000-12-01 Data variables: precipitation (lon, lat, time) float32 ... Attributes: history: Created on xxxx-xx-xx xx:xx |
CopyRight 2018-2019 实验室设备网 版权所有 |