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

问题描述 投票:1回答:1

我正在使用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
1个回答
4
投票

Xarray将Python 2的str / bytes类型映射到NetCDF的NC_CHAR类型。这两种类型都代表单字节字符数据(通常是ASCII),因此这具有一定的意义。

要获取netCDF字符串NC_STRING,您需要传递pass unicode数据(Python 3上的str)。您可以通过使用.astype(unicode)或通过在{'dtype': unicode}中传递encoding来明确地将时间戳列强制转换为unicode来实现此目的。

© www.soinside.com 2019 - 2024. All rights reserved.