【问题标题】:Append data to existing pytables table将数据追加到现有的 pytables 表
【发布时间】:2017-08-16 23:04:50
【问题描述】:

我是 PyTables 的新手,我实现了一些在 Pytables 中从表中插入和检索数据的基本技术。但是,我不确定如何在现有的 PyTables 表中插入数据,因为我在 tutorial 中读取/获取的所有内容都是创建一个新表(使用 h5file.createTable() 方法)。以下是教程中关于将数据插入从头开始创建的 PytTables 表的基本代码:

h5file = openFile("tutorial1.h5", mode = "w", title = "Test file")
group = h5file.createGroup("/", 'detector', 'Detector information')
table = h5file.createTable(group, 'readout', Particle, "Readout example")

for i in xrange(10):
    particle['name']  = 'Particle: %6d' % (i)
    particle['TDCcount'] = i % 256
    particle['ADCcount'] = (i * 256) % (1 << 16)
    particle['grid_i'] = i
    particle['grid_j'] = 10 - i
    particle['pressure'] = float(i*i)
    particle['energy'] = float(particle['pressure'] ** 4)
    particle['idnumber'] = i * (2 ** 34)
    # Insert a new particle record
    particle.append()

    table.flush()

附:本教程中有一个place 讨论将数据附加到现有表,但使用的是从头开始创建的表,基本上不知道选择预先存在的表来附加数据。请帮忙。谢谢。

【问题讨论】:

    标签: python pytables


    【解决方案1】:

    您需要以附加模式"a" 打开您的文件。也不要再次创建组和表。这又追加了 10 行:

    import tables
    
    
    class Particle(tables.IsDescription):
        name      = tables.StringCol(16)   # 16-character String
        idnumber  = tables.Int64Col()      # Signed 64-bit integer
        ADCcount  = tables.UInt16Col()     # Unsigned short integer
        TDCcount  = tables.UInt8Col()      # unsigned byte
        grid_i    = tables.Int32Col()      # 32-bit integer
        grid_j    = tables.Int32Col()      # 32-bit integer
        pressure  = tables.Float32Col()    # float  (single-precision)
        energy    = tables.Float64Col()    # double (double-precision)
    
    h5file = tables.openFile("tutorial1.h5", mode = "a")
    table = h5file.root.detector.readout
    
    particle = table.row
    
    for i in range(10, 20):
        particle['name']  = 'Particle: %6d' % (i)
        particle['TDCcount'] = i % 256
        particle['ADCcount'] = (i * 256) % (1 << 16)
        particle['grid_i'] = i
        particle['grid_j'] = 10 - i
        particle['pressure'] = float(i*i)
        particle['energy'] = float(particle['pressure'] ** 4)
        particle['idnumber'] = i * (2 ** 34)
        # Insert a new particle record
        particle.append()
    
    h5file.close()
    

    【讨论】:

    • @khan 这个解决方案成功了吗?
    • 感谢@Mike,它在 Python 3.5 上完美地为我工作(使用range 而不是xrange)并且应该被标记为答案。如果缺少组和表,我稍微修改了示例以创建它们:gist.github.com/berezovskyi/10004d5fcf00a3d4477e
    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多