问题描述:
若干个nc文件储存全球的1850-2014年月尺度的mrro数据(或其他数据),从1850-1到2014-12一共1980个月,要提取出最后35年1980.1~2014.12年也就是420个月的数据。
代码实现
def aaa(input_file,output_file,bianliang,start_index,end_index):
# 打开输入NetCDF文件
ds = nc.Dataset(input_file, 'r')
# 获取时间变量和mrro变量 这里不一定是mrro变量,名称由传入参数bianliang确定
time_var = ds.variables['time']
mrro_var = ds.variables[bianliang]
time_indices = np.arange(start_index, end_index)
time_data = time_var[time_indices]
mrro_data = mrro_var[time_indices, :, :]
# 创建新的NetCDF文件
new_ds = nc.Dataset(output_file, 'w', format='NETCDF4')
# 创建维度(这些在新数据集中还不存在)
new_ds.createDimension('time', None) # 可变长度维度,或者指定确切长度len(time_data)
lat_dim = new_ds.createDimension('lat', len(ds.dimensions['lat']))
lon_dim = new_ds.createDimension('lon', len(ds.dimensions['lon']))
# 创建新变量
times = new_ds.createVariable('time', time_var.datatype, ('time',))
lats = new_ds.createVariable('lat', ds.variables['lat'].datatype, ('lat',))
lons = new_ds.createVariable('lon', ds.variables['lon'].datatype, ('lon',))
mrro = new_ds.createVariable(bianliang, mrro_var.datatype, ('time', 'lat', 'lon'))
# 复制变量属性
times.setncatts({k: time_var.getncattr(k) for k in time_var.ncattrs()})
lats.setncatts({k: ds.variables['lat'].getncattr(k) for k in ds.variables['lat'].ncattrs()})
lons.setncatts({k: ds.variables['lon'].getncattr(k) for k in ds.variables['lon'].ncattrs()})
mrro.setncatts({k: mrro_var.getncattr(k) for k in mrro_var.ncattrs()})
# 写入数据
times[:] = time_data # 确保time_data是正确的!
lats[:] = ds.variables['lat'][:]
lons[:] = ds.variables['lon'][:]
mrro[:] = mrro_data # 确保mrro_data是正确的!
# 复制全局属性
new_ds.setncatts({k: ds.getncattr(k) for k in ds.ncattrs() if k != 'history'}) # 避免覆盖我们即将设置的历史属性
# 更新历史属性
history = "Created by subsetting the original dataset" # 原始数据集的历史属性可能不包含有用的信息,或者我们想要添加新的信息
new_ds.setncattr('history', history)
# 关闭文件
new_ds.close()
ds.close()
print("完成")
import glob
import netCDF4 as nc
import numpy as np
import os
def get_nc_files(directory):
# 使用 os.path.join 确保路径格式正确
pattern = os.path.join(directory, '*.nc')
nc_files = glob.glob(pattern)
# 如果只需要文件名而不是完整路径,可以使用 os.path.basename 提取
nc_files = [os.path.basename(file) for file in nc_files]
return nc_files
start_index = 1560 # 数据起点
end_index = 1980 # 数据终点
directory_path = './'
nc_files_list = get_nc_files(directory_path)
for ncfile in nc_files_list:
print(ncfile)
input_file = ncfile
s = ''
s += str(ncfile)
output_file = s.replace('185001', '198001')
bianliang = input_file.split('_')[0] # 根据文件名称获取变量名
aaa(input_file,output_file,bianliang,start_index,end_index)
将python文件和待处理文件放一起
运行代码
依赖库
netCDF4
numpy
高版本python直接pip install 安装?
netCDF4
numpy
低版本python(我用的3.7,用pip直接安装netCDF4总报错)
解决办法:
pip install "netCDF4<1.6.0"
安装低版本的netCDF4,搞定。
ps: 代码粗糙,欢迎交流学习。