使用Python截取nc文件数据保存到CSV文件

问题要求:

编写一个函数完成以下任务:截取经度在23°N-40°N,纬度在118°E-131°E范围内各属性不同深度的数据,使用Python中合适的数据结构将截取的数据保存到同名CSV文件中。(nc文件数据格式参见笔者其他文章)

 

 

实验内容(附代码)

  • 实验数据介绍(通过实验介绍你对NC数据的认识)

 

nc文件即NetCDF全称为network Common Data Format,中文译法为“网络通用数据格式”。 一个NetCDF文件的结构包括以下对象:变量(Variables),维(dimension),属性(Attribute) 。

 

本次查看的nc文件其中包括 (['salinity', 'time', 'depth', 'lat', 'lon', 'water_temp']) 一共5个变量。其中’salinity’和’water_temp’两个变量有四个维度,表示为

‘salinity(time, depth, lat, lon)’和’water_temp(time, depth, lat, lon)’。每个变量有自己的属性值,例如纬度’lat’,表示为

float64 lat(lat)

    long_name: Latitude

    standard_name: latitude

    units: degrees_north

    axis: Y

    NAVO_code: 1

    _CoordinateAxisType: Lat

 

 

  • 实验步骤(记录实验过程,配图加以说明)

实验1:简单的安装netCDF4包,然后用这个包下的Dateset函数来读取文件信息。

 

 

 

实验2:

1.设一个函数,然后用Dateset函数读取nc文件

 

 

2.获取变量相应数组集合-纬度经度温度深度

 

 

3.文件路径

  

 

4.创建csv文件,设置异常处理

  这里用嵌套循环将符合条件的值writerow到创建的csv文件中。

  

5.’__name__==__main__’模块

  这个模块的作用是既能保证当前的.py文件能直接运行,也能保证其可以作为模块被其他.py文件导入。

  

 

  • 实验结果

成功生成了对应的csv文件。其中共有34345行数据。

 

 

 

 

  • 实验参考资料

 

参考博客:

如何在PyCharm中安装第三方库(包)?

http://www.360doc.com/content/18/0822/17/11881101_780384182.shtml

 

NC文件读写方式

https://blog.csdn.net/ennaymonkey/article/details/62886843

 

Python读取nc文件

https://blog.csdn.net/showpingzhang/article/details/83384780

 

Python读写csv文件的几种方法 及 pandas.read_csv参数全解

https://blog.csdn.net/secondlieutenant/article/details/79157956

 

 

  • 实验总结与体会

本次实验是我第一次使用python来处理数据集。通过本次实验,

  1. 加深了对nc文件的认识。
  2. 对python处理数据的方法有了一定了解。
  3. 对python用于数据处理计算的库例如netCDF4和numpy有了一定了解。
  4. 对于python的文件操作有了一定认识。
import pandas
import netCDF4 as ne
import numpy as np
import  csv
import glob
import  sys

def to_csv(source_file):
    #读取nc数据
    dataset=ne.Dataset(source_file)
    print(dataset.variables.keys())

    #获取相应数组集合--纬度经度温度深度
    lat_set = dataset.variables['lat'][:]
    lon_set = dataset.variables['lon'][:]
    temp_set=dataset.variables['water_temp'] [:]
    dep_set=dataset.variables['depth'][:]

    index = []  # 把满足条件的经纬度放入列表index之中
    for j in range(len(lat_set)):  # j为纬度
        for k in range(len(lon_set)):  # k为经度
            if lat_set[j] > 23 and lat_set[j] < 40:
                if lon_set[k] > 118 and lon_set[k] < 131:
                    index.append((j, k))  # 插入满足条件的数据
    print('输出index列表:')
    print(index)
    print('-------------------------------------------------------------------')
    #文件名不含扩展名
    source_file=source_file.split('.')
    file_name=source_file[0]

    #创建csv目标文件
    try:
        #打开目标csv文件
        with open(file_name+'.csv','a',newline='') as targetFile:
            # 创建写入流
            writer = csv.writer(targetFile)
            # 写入表头
            writer.writerow(('lat', 'lon', 'temperature',  'depth',
                             ))
            # 写入数据
            for j in range(len(lat_set)):  # j为纬度
                for k in range(len(lon_set)):  # k为经度
                    if lat_set[j] > 23 and lat_set[j] < 40:
                        if lon_set[k] > 118 and lon_set[k] < 131:
                            i=0
                            writer.writerow((lat_set[j], lon_set[k], temp_set[0][i][j][k],  dep_set[i]))

        targetFile.close()#关闭文件
        print('Get'+file_name+'.csv Success!')
    except Exception as e:#抛异常
        print('Error :'+str(e))


if '__name__ ==__main__':
    print("start transfrom!")
    to_csv('20150101.nc')
    print('Transform successfully')

 

  • 11
    点赞
  • 104
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值