【问题标题】:pytables and pandas string padding questionpytables 和 pandas 字符串填充问题
【发布时间】:2020-11-20 20:55:20
【问题描述】:

我使用 hdf5cpp 库创建了一个数据集,该库具有固定大小的字符串(要求)。但是,当使用 pytables 或 pandas 加载时,字符串总是表示为:

b'test\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff

'test' 的字符串值,后面有填充。有谁知道抑制或不显示此填充数据的方法?我真的只想显示“测试”。我意识到这可能是正确的行为。

我的字符串 hdf5cpp 设置:

strType = H5Tcopy(H5T_C_S1);
status = H5Tset_size(strType, 36);
H5Tset_strpad(strType, H5T_STR_NULLTERM);

【问题讨论】:

    标签: python pandas hdf5 pytables


    【解决方案1】:

    我对你的 C 代码无能为力。可以在 Pytables 中使用填充字符串。我可以读取由 C 应用程序编写的数据,该应用程序创建混合类型的结构数组,包括填充字符串。 (注意:有一个与复制带有填充的 NumPy 结构数组有关的问题。它已在 3.5.0 中修复。阅读此内容了解详细信息:PyTables GitHub Pull 720。)

    这是一个示例,显示了使用 PyTables 创建的文件进行正确的字符串处理。也许它会帮助你调查你的问题。检查数据集的属性将是一个好的开始。

    import tables as tb
    import numpy as np
    
    arr = np.empty((10), 'S10')
    arr[0]='test'
    arr[1]='one'
    arr[2]='two'
    arr[3]='three'
    
    with tb.File('SO_63184571.h5','w') as h5f:
        ds = h5f.create_array('/', 'testdata', obj=arr)
        print (ds.atom)
        
        for i in range(4):
            print (ds[i])
            print (ds[i].decode('utf-8'))
    

    添加了以下示例以演示具有 int 和固定字符串的复合数据集。这在 PyTables 中称为Table(数组始终包含同质值)。这可以通过多种方式完成。我展示了两种我喜欢的方法:

    1. 创建记录数组并使用description= 或引用 obj= 参数。这在您已经拥有所有数据并且可以放入内存时很有用。
    2. 创建记录数组 dtype 并使用 description= 引用 范围。然后使用.append() 方法添加数据。这是 当您的所有数据都无法放入内存中时很有用,或者您需要将数据添加到现有表中。

    代码如下:

    recarr_dtype = np.dtype( 
                    { 'names':   ['ints', 'strs' ], 
                      'formats': [int, 'S10'] } )
    a = np.arange(5)
    b = np.array(['a', 'b', 'c', 'd', 'e']) 
    recarr = np.rec.fromarrays((a, b), dtype=recarr_dtype) 
    
    with tb.File('SO_63184571.h5','w') as h5f:
        ds1 = h5f.create_table('/', 'compound_data1', description=recarr)
        
        for i in range(5):
            print (ds1[i]['ints'], ds1[i]['strs'].decode('utf-8'))
    
        ds2 = h5f.create_table('/', 'compound_data2', description=recarr_dtype)
        ds2.append(recarr)
        
        for i in range(5):
            print (ds2[i]['ints'], ds2[i]['strs'].decode('utf-8'))
        
    

    【讨论】:

    • 谢谢,是否可以发布包含和 int 和固定字符串的复合数据集?我注意到 pytables 添加了很多结构性添加..
    猜你喜欢
    • 2010-10-20
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 2017-04-11
    • 2017-11-28
    • 2018-01-23
    相关资源
    最近更新 更多