当前位置: 首页 > news >正文

python裁剪nc文件数据

问题描述:

若干个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: 代码粗糙,欢迎交流学习。

相关文章:

  • Codeforces Round 1011 (Div. 2)
  • shopify跨境电商行业前景与规模
  • 类和对象—封装
  • 【算法】动态规划:回文子串问题、两个数组的dp
  • RWEQ+集成技术在风蚀模数估算中的全流程增强策略—从数据融合到模型耦合的精细化操作指南
  • 05、Tools
  • OSI模型_TCP/IP模型_五层模型
  • Thales靶场
  • Netty源码—6.ByteBuf原理二
  • AI Agent开发大全第十一课-超维空间里的语义翻译官:Embedding技术
  • 个人学习编程(3-25) leetcode刷题
  • Linux 练习二 LVS的NAT模式
  • 从C语言开始的C++编程生活(2)
  • Java基础关键_028_线程(一)
  • 3.24前端模拟面试
  • C语言基础系列【28】指针进阶1:深入理解指针
  • go test相关命令
  • 医院挂号预约小程序|基于微信小程序的医院挂号预约系统设计与实现(源码+数据库+文档)
  • Tomcat相关的面试题
  • T113-S3-启动报错tee_readfdt:433finenode/firmware/opteefailedwith FDT_ERR_NOTFOUND
  • 青岛企业如何建网站/最新热点新闻
  • 做网站哪个部分/实时新闻
  • 采集类淘宝客网站怎么做/深圳优化公司找高粱seo服务
  • 深圳建网站公司哪家好/北大青鸟软件开发培训学费多少
  • 网站开发 项目接单/网络优化app
  • 淘客做自己的网站/深圳网站优化公司