xarray - 将字符串存储为'string'数据类型,而不是 Python2.7 的'char'(n 维字符数组)



我使用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

xarray映射python 2的 str/ bytes类型为netcdf的 NC_CHAR类型。这两种类型都代表单个字节字符数据(通常是ASCII(,因此这具有一定的意义。

要获得NetCDF字符串NC_STRING,您需要通过unicode数据(Python 3上的str(。您可以通过.astype(unicode)或通过encoding中的{'dtype': unicode}明确胁迫您的时间戳列来获得此功能。

最新更新