sai*_*iak 2 python netcdf python-xarray netcdf4 xarray
我正在使用 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)
Run Code Online (Sandbox Code Playgroud)
当我使用 Python3.6 对 op_file.nc 进行 ncdump 时,我得到:
netcdf op_file {
dimensions:
time = UNLIMITED ; // (24 currently)
variables:
string timestamp(time) ;
float air_temp(time) ;
.
.
.
Run Code Online (Sandbox Code Playgroud)
当我使用 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) ;
.
.
.
Run Code Online (Sandbox Code Playgroud)
示例输入文件如下所示:
# 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
Run Code Online (Sandbox Code Playgroud)
Xarray 将 Python 2 的str/bytes类型映射到 NetCDF 的NC_CHAR类型。这两种类型都表示单字节字符数据(通常是 ASCII),所以这在一定程度上是有意义的。
要获取 netCDF 字符串NC_STRING,您需要传递传递unicode数据(str在 Python 3 上)。你可以明确地强迫你timestamp列到Unicode,要么得到这个.astype(unicode)或传递{'dtype': unicode}在encoding。
| 归档时间: |
|
| 查看次数: |
1010 次 |
| 最近记录: |