【发布时间】:2018-08-04 04:18:53
【问题描述】:
我正在使用 xarray 将文本文件转换为 netCDF 格式。当我使用 netCDF4 格式和 Python3 时,它将字符串变量存储为字符串,但当我使用 Python2 时,它将它们存储为 n 维字符数组。我试图在编码中设置 dtype='str' 并没有任何区别。有没有办法使用 Python2 使这些变量具有字符串数据类型?任何想法将不胜感激。
这是我的代码:
import pandas as pd
import xarray as xr
column_names = ['timestamp', 'air_temp', 'vtempdiff', 'rh', 'pressure', 'wind_dir', 'wind_spd']
df = pd.read_csv(args.input_file, skiprows = 1, header=None, names = column_names)
ds = xr.Dataset.from_dataframe(df)
encoding = {'timestamp': {'dtype': 'str'},
'air_temp': {'_FillValue': 9.96921e+36, 'dtype': 'f4'}
}
ds.to_netcdf(op_file.nc, format = 'NETCDF4', unlimited_dims={'time':True}, encoding = encoding)
当我使用 Python3.6 对 op_file.nc 进行 ncdump 时,我得到:
netcdf op_file {
dimensions:
time = UNLIMITED ; // (24 currently)
variables:
string timestamp(time) ;
float air_temp(time) ;
.
.
.
当我使用 Python2.7 时,我得到:
netcdf op_file {
dimensions:
time = UNLIMITED ; // (24 currently)
string20 = 20 ;
variables:
char timestamp(time, string20) ;
timestamp:_Encoding = "utf-8" ;
float air_temp(time) ;
.
.
.
示例输入文件如下所示:
# Fields: stamp,AGO-4.air_temp,AGO-4.vtempdiff,AGO-4.rh,AGO-4.pressure,AGO-4.wind_dir,AGO-4.wind_spd
2016-11-30T00:00:00Z,-36.50,,56.00,624.60,269.00,5.80
2016-11-30T01:00:00Z,-35.70,,55.80,624.70,265.00,5.90
【问题讨论】:
-
那是一大堆不相关的代码。给出一个简单的玩具示例,以最小的数据大小显示您的问题。在这种情况下,可能一个值就足够了,而不是半打列。
标签: python netcdf python-xarray netcdf4 xarray