import netCDF4 import geopandas as gpd import numpy as np import pandas as pd # 加载nc文件 nc_file = netCDF4.Dataset('E:/data/temp_CMFD_V0106_B-01_01mo_010deg_197901-201812.nc') temp_data = nc_file.variables['temp'][:] # 加载shp文件 shp_file = gpd.read_file('D:/dilidashuju/shijiquhua.shp') # 计算每个市级行政区的平均温度 years = range(1979, 2018) months = range(1, 13) temp_df = pd.DataFrame(columns=['year', 'month', 'city', 'temperature']) for year in years: for month in months: temp_array = temp_data[(year-1979)*12+month-1, :, :] for i, row in shp_file.iterrows(): city_name = row['市'] city_geom = row['geometry'] temp_mean = np.mean(temp_array[np.array([city_geom.contains(Point(lon, lat)) for lon, lat in zip(temp_array.lon, temp_array.lat)])]) temp_df = temp_df.append({'year': year, 'month': month, 'city': city_name, 'temperature': temp_mean}, ignore_index=True) # 将结果保存到CSV文件中 temp_df.to_csv('city_temperature.csv', index=False)这串代码报错Traceback (most recent call last): File "C:\Users\Lenovo\PycharmProjects\pythonditu\main.py", line 24, in <module> temp_mean = np.mean(temp_array[np.array([city_geom.contains(Point(lon, lat)) for lon, lat in zip(temp_array.lon, temp_array.lat)])]) AttributeError: 'MaskedArray' object has no attribute 'lon'怎么修改
时间: 2024-03-21 08:44:07 浏览: 15
这个错误是因为 `temp_array` 是一个 `MaskedArray` 对象,它不能像普通的 numpy 数组那样直接使用索引访问变量。要解决此错误,可以使用 `data` 属性来访问 `temp_array` 的实际数据数组,如下所示:
```
temp_mean = np.mean(temp_array.data[np.array([city_geom.contains(Point(lon, lat)) for lon, lat in zip(temp_array.lon, temp_array.lat)])])
```
这将使用列表推导式为 `temp_array` 中的每个点创建一个包含 True 或 False 的数组,并将其传递给 `temp_array.data`,以便获取在 `city_geom` 中的温度值。
相关问题
import matplotlib.pyplot as plt import numpy as np import netCDF4 as nc import cartopy.crs as ccrs from cartopy.util import add_cyclic_point
I'm sorry, as an AI language model, I am not capable of displaying images or visualizations. However, I can provide you with the code for displaying a map using Cartopy and NetCDF4. Here's an example code:
```
import matplotlib.pyplot as plt
import numpy as np
import netCDF4 as nc
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
# Load the NetCDF data
data = nc.Dataset('data.nc')
# Extract the variables
lon = data.variables['lon'][:]
lat = data.variables['lat'][:]
temp = data.variables['temp'][:]
# Add a cyclic point for plotting
temp, lon = add_cyclic_point(temp, coord=lon)
# Create a map projection
projection = ccrs.PlateCarree()
# Create a figure and axis
fig, ax = plt.subplots(subplot_kw={'projection': projection})
# Add coastlines
ax.coastlines()
# Plot the data
plt.contourf(lon, lat, temp, cmap='coolwarm', transform=projection)
# Add a colorbar
plt.colorbar()
plt.show()
```
In this example, we first load the NetCDF data and extract the variables we need. We then add a cyclic point to the temperature data to ensure it wraps around the plot correctly. Next, we create a map projection and a figure with an axis that uses the projection. We add coastlines to the plot and use `plt.contourf()` to plot the temperature data on the map. Finally, we add a colorbar to the plot and display it using `plt.show()`.
代码是# -*- coding: utf-8 -*- # import arcpy import netCDF4 as nc # 将nc文件选择变量后转成tif图层成功 nc_file = nc.Dataset('F:/nc_data/1979_sd.nc', 'r') # 获取变量 var2 = nc_file.variables['rsn'] var1 = nc_file.variables['sd'] # 将变量中的数据相加 new_var_data = 10*var1[:] / var2[:] # 创建新的.nc文件 new_nc_file = nc.Dataset('1979_sd_1.nc', 'w') # 定义.nc文件的维度 new_nc_file.createDimension('lat', var1.shape[0]) new_nc_file.createDimension('lon', var1.shape[1]) # 定义新的变量 new_var = new_nc_file.createVariable('new_variable', 'f4', ('lat', 'lon')) # 将新变量的数据写入新的.nc文件 new_var[:] = new_var_data # 关闭文件 nc_file.close() new_nc_file.close()
在你的代码中,`var1` 和 `var2` 可能是两个不同形状的数组。具体来说,`var1` 和 `var2` 可能有不同的维度,或者在某个维度上的长度不同,从而导致在计算 `new_var_data` 时出现了 shape mismatch 的错误。
你可以通过打印 `var1` 和 `var2` 的形状,以及它们在各个维度上的长度,来检查这个问题。具体代码如下:
```python
import netCDF4 as nc
nc_file = nc.Dataset('F:/nc_data/1979_sd.nc', 'r')
var1 = nc_file.variables['sd']
var2 = nc_file.variables['rsn']
print(var1.shape)
print(var2.shape)
print(var1.shape[0], var2.shape[0])
print(var1.shape[1], var2.shape[1])
```
运行这段代码后,将会输出 `var1` 和 `var2` 的形状以及它们在各个维度上的长度。你可以根据这些信息来判断 `var1` 和 `var2` 是否有不同的维度或者长度,从而找到并解决 shape mismatch 的问题。