import xarray as xr import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs def readdat(pth,var): ds = xr.open_dataset(pth) dat = ds[var].values lon=ds['lon'] lat=ds['lat'] # 只读取每年1月的数据 dat = dat.sel(time=dat['time.month'].isin([1])) dat = dat.loc['1981-01-01':'2018-12-01','500',:,:] return lon,lat,dat AttributeError: 'numpy.ndarray' object has no attribute 'sel'
时间: 2024-01-26 18:02:40 浏览: 141
这个错误提示是因为你在一个 `numpy.ndarray` 上使用了 `.sel()` 这个 xarray.Dataset 特有的方法。你需要将 `dat` 变量转换成 xarray 的 Dataset 或者 DataArray 类型才能使用 `.sel()` 方法。
你可以尝试将以下代码:
```
dat = dat.sel(time=dat['time.month'].isin([1]))
dat = dat.loc['1981-01-01':'2018-12-01','500',:,:]
```
改成:
```
dat = xr.DataArray(dat, coords=[ds['time'], ds['level'], ds['lat'], ds['lon']], dims=['time', 'level', 'lat', 'lon'])
dat = dat.sel(time=dat['time.month'].isin([1]))
dat = dat.loc['1981-01-01':'2018-12-01', 500, :, :]
```
这样就可以使用 `.sel()` 方法来选择数据了。
相关问题
import matplotlib.pyplot as plt from mpl_toolkits. basemap import Basemap import xarray as xr import pandas as pd import numpy as np import netCDF4 as nc import cartopy.crs as ccrs ds = xr.open_dataset('correlation.1.30.160.200.191.3.13.51.nc') plt.subplot(1,1,1) ds.hgt.plot() plt.show() projection=ccrs.Orthographic(central_latitude=90, central_longitude=0) fig=plt.figure(figsize=(8,8)) ax=plt.axes(projection=projection) ax.coastlines() ax.set_global() ax.axhline(0,color='black') ax.axvline(0,color='black') ds=nc.Dataset('correlation.1.30.160.200.191.3.13.51.nc') lon=ds.variables['lon'][:] lat=ds.variables['lat'][:] time_index=0 variable=ds.variables['hgt'][time_index,:,:] lonlon,latlat=np.meshgrid(lon,lat) plt.scatter(lonlon,latlat) plt.contourf(lon,lat,variable,cmap='jet') data = ds.variables['time'][:] long = ds.variables['lon'][:] lati = ds.variables['lat'][:] plt.colorbar(label="Sif", orientation="horizontal") cbar=plt.colorbar plt.title('Jan 1948 to 2020: 1000mb Geopotential Height \n Seasonal Correlation w/ Jan SOI \n NCEP /NCAR Reanalysis') plt.show() plt.savefig('12.pdf')给代码改错
根据您提供的代码,我注意到其中可能存在一些错误。以下是我对代码的修改建议:
```python
import matplotlib.pyplot as plt
import xarray as xr
import cartopy.crs as ccrs
ds = xr.open_dataset('correlation.1.30.160.200.191.3.13.51.nc')
plt.subplot(1, 1, 1)
ds.hgt.plot()
plt.show()
projection = ccrs.Orthographic(central_latitude=90, central_longitude=0)
fig = plt.figure(figsize=(8, 8))
ax = plt.axes(projection=projection)
ax.coastlines()
ax.set_global()
ax.axhline(0, color='black')
ax.axvline(0, color='black')
lon = ds['lon'][:]
lat = ds['lat'][:]
time_index = 0
variable = ds['hgt'][time_index, :, :]
lonlon, latlat = np.meshgrid(lon, lat)
plt.scatter(lonlon, latlat)
plt.contourf(lon, lat, variable, cmap='jet')
data = ds['time'][:]
long = ds['lon'][:]
lati = ds['lat'][:]
plt.colorbar(label="Sif", orientation="horizontal")
plt.title('Jan 1948 to 2020: 1000mb Geopotential Height \n Seasonal Correlation w/ Jan SOI \n NCEP/NCAR Reanalysis')
plt.show()
plt.savefig('12.pdf')
```
这些修改主要包括:
- 移除了无关模块的导入语句(如`mpl_toolkits.basemap`和`pandas`)。
- 修改了获取经度(`lon`)和纬度(`lat`)的方式。
- 修改了获取变量数据(`variable`)的方式。
- 移除了未使用的变量(`data`、`long`和`lati`)。
- 修正了`colorbar`的调用方法。
- 修正了图表标题的格式。
请注意,代码中使用的数据文件路径可能需要根据您的实际情况进行修改。另外,如果还有其他错误或需要进一步的调整,请提供更多详细信息。
import xarray as xr import matplotlib.pyplot as plt from netCDF4 import Dataset import cartopy.crs as ccrs#投影方式 import cartopy.feature as cfeature import cartopy.io.shapereader as shpreader import numpy as np import pandas as pd from matplotlib.font_manager import fontManager da=pd.read_csv(r'E:\python11\STATION_58237.txt',sep='\s+') print(da) tem=da['TEM'] #print(tem.shape) rhu=da['RHU'] tem_ave=[] for i in range(0,24): tem_data=tem[i:147:24] print(tem_data) tem_ave[i]=np.mean(tem_data) print(tem_ave) plt.plot(tem_ave)帮我改一下
import xarray as xr
import matplotlib.pyplot as plt
from netCDF4 import Dataset
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import cartopy.io.shapereader as shpreader
import numpy as np
import pandas as pd
from matplotlib.font_manager import fontManager
da = pd.read_csv(r'E:\python11\STATION_58237.txt', sep='\s+')
print(da)
tem = da['TEM']
rhu = da['RHU']
tem_ave = []
for i in range(0, 24):
tem_data = tem[i:147:24]
print(tem_data)
tem_ave.append(np.mean(tem_data)) # 将结果添加到列表中
print(tem_ave)
plt.plot(tem_ave)
plt.show() # 显示图形
阅读全文