我尝试将我的数据从一个大的netCDF文件转换为一个特殊点的ascii格式文件(68,21)。当我尝试运行以下内容时:
from pylab import *
from netCDF4 import Dataset
import pandas as pd
nc = Dataset("/home/python/PBLH_Exp_08_Jul_2006.nc")
PBLH = nc.variables['PBLH'][:,:,:]
Times = nc.variables['Times'][:,:]
d={}
d['Times'] = Times[:,0]
d['PBLH'] = PBLH[:,:,1]
df=pd.DataFrame(d)
df.to_csv('Produkt/PBLH_Exp_08_Jul_2006.csv')
我收到了错误消息:
Traceback (most recent call last):
File "/home/python/wrf_map.py", line 62, in <module>
df=pd.DataFrame(d)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 226, in __init__
mgr = self._init_dict(data, index, columns, dtype=dtype)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 363, in _init_dict
dtype=dtype)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 5163, in _arrays_to_mgr
arrays = _homogenize(arrays, index, dtype)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 5477, in _homogenize
raise_cast_failure=False)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 2885, in _sanitize_array
raise Exception('Data must be 1-dimensional')
Exception: Data must be 1-dimensional
我该怎么做才能解决这个问题?如何为网格点提取数据?顺便说一句,这是我的netCDF文件的标题的一部分:
<xarray.Dataset>
Dimensions: (Time: 744, south_north: 140, west_east: 140)
Coordinates:
* Time (Time) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...
* south_north (south_north) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...
* west_east (west_east) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ...
Data variables:
Times (Time) |S19 '2006-07-01_01:00:00' '2006-07-01_02:00:00' ...
PBLH (Time, south_north, west_east) float32 59.9834 59.8574 ...
感谢您的帮助!!
答案 0 :(得分:2)
我解决了我的一部分问题。我使用xarray
来获取我想要的数据(对于具有网格点21,68的位置):
import numpy as np
import xray as xr
from pylab import *
data = xr.open_dataset("/home/python/PBLH_Exp_08_jul_2006.nc")
d = xr.DataArray(data.variables['PBLH'])
print(d[:,21,68])
但我仍然无法将数据保存在ASCII文件中......
编辑:知道了!为了保存我的数据,我使用了import csv
。然后我写道:
df = d[:,21,68]
with open ('/home/python/output.txt','w') as fout:
writer = csv.writer(fout)
writer.writerows(df)
它看起来不那么漂亮,但我可以处理它!所以这应该适用于所有有类似问题的人! :)