我的目标是从netcdf文件中访问数据,并以以下格式将其写入CSV文件。
Latitude Longitude Date1 Date2 Date3
100 200 <-- MIN_SFC values -->
到目前为止,我已经访问了变量,将标题写入文件并填充了纬度/经度。
如何访问指定经纬度坐标和日期的MIN_SFC值,然后将其写入CSV文件。
如果有更好的方法,请告诉我,我是Python新手。
NetCDF文件信息:
Dimensions:
time = 7
latitude = 292
longitude =341
Variables:
float MIN_SFC (time=7, latitude = 292, longitude = 341)
Here's what I've tried:
from netCDF4 import Dataset, num2date
filename = "C:/filename.nc"
nc = Dataset(filename, 'r', Format='NETCDF4')
print nc.variables
print 'Variable List'
for var in nc.variables:
print var, var.units, var.shape
# get coordinates variables
lats = nc.variables['latitude'][:]
lons = nc.variables['longitude'][:]
sfc= nc.variables['Min_SFC'][:]
times = nc.variables['time'][:]
# convert date, how to store date only strip away time?
print "Converting Dates"
units = nc.variables['time'].units
dates = num2date (times[:], units=units, calendar='365_day')
#print [dates.strftime('%Y%m%d%H') for date in dates]
header = ['Latitude', 'Longitude']
# append dates to header string
for d in dates:
print d
header.append(d)
# write to file
import csv
with open('Output.csv', 'wb') as csvFile:
outputwriter = csv.writer(csvFile, delimiter=',')
outputwriter.writerow(header)
for lat, lon in zip(lats, lons):
outputwriter.writerow( [lat, lon] )
# close the output file
csvFile.close()
# close netcdf
nc.close()
更新:
我已经更新了写入CSV文件的代码,因为经度/纬度是双精度浮点数而导致了一个属性错误。
AttributeError: 'numpy.float32' object has no attribute 'append'
在Python中有任何方法可以转换为字符串吗?你认为这样会行吗?
我注意到在将数值打印到控制台时,有一些值被返回为“-”符号。我想知道这是否代表了填充值或缺失值,其定义为-32767.0。
我也想知道3D数据集的变量应该通过lats = nc.variables ['latitude'][:] [:]还是 lats = nc.variables['latitude'][:][:,:]来访问?
# the csv file is closed when you leave the block
with open('output.csv', 'wb') as csvFile:
outputwriter = csv.writer(csvFile, delimiter=',')
for time_index, time in enumerate(times): # pull the dates out for the header
t = num2date(time, units = units, calendar='365_day')
header.append(t)
outputwriter.writerow(header)
for lat_index, lat in enumerate(lats):
content = lat
print lat_index
for lon_index, lon in enumerate(lons):
content.append(lon)
print lon_index
for time_index, time in enumerate(times): # for a date
# pull out the data
data = sfc[time_index,lat_index,lon_index]
content.append(data)
outputwriter.writerow(content)
numpy.savetxt
函数将其写入文本文件,具体文档可以在这里查阅 (http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html)。 - Spencer Hillnumpy.savetxt
有header
和delimiter
参数。前者可以让你指定你想要的顶部行,后者可以让你根据需要插入制表符来创建所需的列。访问Numpy数组的子集(即您想要的纬度和经度范围)的最佳方法是通过Numpy的切片。 - Spencer Hill