2013-05-28 30 views
5

Tôi mới dùng PyTables và triển khai một số kỹ thuật cơ bản về chèn và lấy dữ liệu từ bảng trong Pytables. Tuy nhiên, tôi không chắc chắn về cách chèn dữ liệu vào bảng PyTables hiện có vì tất cả những gì tôi đọc/nhận trong tutorial là tạo một bảng mới (sử dụng phương thức h5file.createTable()). Đây là mã cơ bản mà hướng dẫn có về chèn dữ liệu vào bảng PytTables được tạo từ đầu:Nối dữ liệu vào bảng pytables hiện có

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() 

P.S. Có một place trong hướng dẫn này nói về việc thêm dữ liệu vào bảng hiện có, nhưng sử dụng bảng được tạo từ đầu và về cơ bản không có ý tưởng về việc chọn bảng có sẵn để thêm dữ liệu. Giúp đỡ một cách tử tế. Cảm ơn.

Trả lời

11

Bạn cần mở tệp của mình ở chế độ phụ thêm "a". Cũng không tạo lại nhóm và bảng. Cột này nối thêm 10 hàng khác:

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() 
+1

@khan Bất kỳ thành công nào với giải pháp này? –

+0

Cảm ơn @Mike, nó làm việc cho tôi một cách hoàn hảo trên Python 3.5 (với 'phạm vi' thay vì' xrange') và phải được đánh dấu là câu trả lời. Tôi đã sửa đổi một chút ví dụ để tạo nhóm và bảng nếu chúng bị thiếu: https://gist.github.com/berezovskyi/10004d5fcf00a3d4477e – berezovskyi

Các vấn đề liên quan