- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我的目标是从 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)
这是我尝试过的:
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 文件的代码,有一个属性错误,因为纬度/经度是 double 的。
AttributeError: 'numpy.float32' 对象没有属性 'append'
有什么方法可以在 python 中转换为字符串?你认为它会起作用吗?
当我将值打印到控制台时,我注意到许多值返回为“--”。我想知道这是否表示定义为 -32767.0 的 fillValue 或 missingValue。
我还想知道是否应该通过 lats = nc.variables['latitude'][:][:] 或 lats = nc.variables['latitude'][:][ 访问 3d 数据集的变量:,:] ?
# 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)
最佳答案
我会将数据加载到 Pandas 中,这有助于分析和绘制时间序列数据,以及写入 CSV。
这是一个真实的工作示例,它从全局预测模型数据集中的指定经纬度位置提取波高的时间序列。
注意:这里我们访问一个 OPeNDAP 数据集,这样我们就可以从远程服务器中提取我们需要的数据,而无需下载文件。但是 netCDF4 对于删除的 OPeNDAP 数据集或本地 NetCDF 文件的工作方式完全相同,这是一个非常有用的功能!
import netCDF4
import pandas as pd
import matplotlib.pyplot as plt
# NetCDF4-Python can read a remote OPeNDAP dataset or a local NetCDF file:
url='http://thredds.ucar.edu/thredds/dodsC/grib/NCEP/WW3/Global/Best'
nc = netCDF4.Dataset(url)
nc.variables.keys()
lat = nc.variables['lat'][:]
lon = nc.variables['lon'][:]
time_var = nc.variables['time']
dtime = netCDF4.num2date(time_var[:],time_var.units)
# determine what longitude convention is being used [-180,180], [0,360]
print lon.min(),lon.max()
# specify some location to extract time series
lati = 41.4; loni = -67.8 +360.0 # Georges Bank
# find closest index to specified value
def near(array,value):
idx=(abs(array-value)).argmin()
return idx
# Find nearest point to desired location (could also interpolate, but more work)
ix = near(lon, loni)
iy = near(lat, lati)
# Extract desired times.
# 1. Select -+some days around the current time:
start = dt.datetime.utcnow()- dt.timedelta(days=3)
stop = dt.datetime.utcnow()+ dt.timedelta(days=3)
# OR
# 2. Specify the exact time period you want:
#start = dt.datetime(2013,6,2,0,0,0)
#stop = dt.datetime(2013,6,3,0,0,0)
istart = netCDF4.date2index(start,time_var,select='nearest')
istop = netCDF4.date2index(stop,time_var,select='nearest')
print istart,istop
# Get all time records of variable [vname] at indices [iy,ix]
vname = 'Significant_height_of_wind_waves_surface'
#vname = 'surf_el'
var = nc.variables[vname]
hs = var[istart:istop,iy,ix]
tim = dtime[istart:istop]
# Create Pandas time series object
ts = pd.Series(hs,index=tim,name=vname)
# Use Pandas time series plot method
ts.plot(figsize(12,4),
title='Location: Lon=%.2f, Lat=%.2f' % ( lon[ix], lat[iy]),legend=True)
plt.ylabel(var.units);
#write to a CSV file
ts.to_csv('time_series_from_netcdf.csv')
两者都创建此图以验证您是否已获得所需的数据:
并将所需的 CSV 文件 time_series_from_netcdf.csv
写入磁盘。
关于python - 如何使用 Python 读取 NetCDF 文件并写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420988/
我有两个 csv 文件 file1.csv 和 file2.csv。 file1.csv 包含 4 列。 文件1: Header1,Header2,Header3,Header4 aaaaaaa,bb
我想知道是否有任何方法可以在导入数据库之前测试 CSV 文件? 我有一个包含多列的巨大 CSV 文件,每列都有不同的数据类型和大小。如何测试生成的 CSV 文件中出现的数据是否与每列的大小一致? 还有
我正在从 SCOM 中提取服务器列表,并希望根据包含以下数据的 CSV 检查此列表: Computername,Collection Name Server01,NA - All DA Servers
我有一个包含 24 列的 csv 文件。其中我只想阅读 3 列。我看到 super CSV 是一个非常强大的库,但我不知道如何部分读取 CSV。 partial reading上的链接坏了。 请帮我举
我正在尝试将加特林日志文件导出到 CSV,因为我需要更新 google 电子表格中的所有全局值,因为我的经理需要电子表格中的值。 最佳答案 此 CSV 文件被删除并替换为 JSON 文件,名为 glo
我对 csv 是结构化数据还是半结构化数据感到困惑。 就像 RDBMS 是一个有关系的结构化数据,但 csv 没有关系。 我无法找到确切的答案。 最佳答案 我可以说,具有恒定列和行(二维)的 CSV
我正在使用 pipes-csv 库读取一个 csv 文件。我想先读第一行,然后再读其余的。不幸的是,在 Pipes.Prelude.head 函数返回之后。管道正在以某种方式关闭。有没有办法先读取 c
起初这似乎很明显,但现在我不太确定。 如果 CSV 文件具有以下行: a, 我会将其解释为具有值“a”和“”的两个字段。但是然后查看一个空行,我可以很容易地争辩说它表示一个值为“”的字段。 我接受文件
我正在尝试将列表字典写入 CSV 文件。我希望这些键是 CSV 文件的标题,以及与该键关联的列中的每个键关联的值。 如果我的字典是: {'600': [321.4, 123.5, 564.1, 764
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 10 年前。 Improve thi
是否有任何官方方法允许 CSV 格式的文件允许评论,无论是在其自己的行上还是在行尾? 我尝试检查wikipedia关于此以及RFC 4180但两者都没有提到任何让我相信它不是文件格式的一部分的内容,所
我有一些 csv 格式的数据。然而它们已经是一个字符串,因为我是从 HTTP 请求中获取它们的。我想使用数据框来查看数据。但是我不知道如何解析它,因为 CSV 包只接受文件,而不接受字符串。 一种解决
我有一个 CSV 文件,其中包含一些字段的值列表。它们作为 HTML“ul”元素存储在数据库中,但我想将它们转换为对电子表格更友好的东西。 我应该使用什么作为分隔符?我可以使用转义的逗号、竖线、分号或
我使用 Google 表格(电子表格)来合并我的 Gambio 商店的不同来源的文章数据。要导入数据,我需要在 .csv 文件中使用管道符号作为分隔符/分隔符,并使用 "作为文本分隔符。在用于导出为
这是一个奇怪的请求,因为我们都知道数据库头不应该包含空格。 但是,我正在使用的系统需要在其标题中使用空格才能导入。 我创建了一个 Report Builder 报告,它将数据构建到一个表中,并在我运行
我有一个 .csv 文件,我需要将其转换为 coldfusion 查询。我使用了 cflib.org CSVtoQuery 方法,它工作正常......但是...... 如果 csv 中的“单元格”在
我想知道是否有任何方法可以生成文化中性 CSV 文件,或者至少指定文件中存在的特定列的数据格式。 例如,我生成了包含带小数点分隔符 (.) 的数字的 CSV 文件,然后 将其传递给小数点分隔符为 (,
我正在构建一个 CSV 字符串 - 因此用户单击 div 的所有内容 - 5 个字符的字符串都会传递到隐藏字段中 - 我想做的是附加每个新值并创建一个 CSV 字符串 - 完成后- 在文本框中显示 -
我正在努力从另外两个文件创建一个 CSV 文件 这是我需要的 我想要的文件(很多其他行) “AB”;“A”;“B”;“C”;“D”;“E” 我拥有的文件: 文件 1:"A";"B";"C";"D";"
我正在尝试将表导出到配置单元中的本地 csv 文件。 INSERT OVERWRITE LOCAL DIRECTORY '/home/sofia/temp.csv' ROW FORMAT DELIMI
我是一名优秀的程序员,十分优秀!