2013-05-28 21 views
5

私はPyTablesを初めて使い、Pytablesのテーブルからデータを挿入したり取り出したりする基本的な手法をいくつか実装しました。しかし、私がtutorialで読んだり取得したものが新しいテーブルを作成しているので(h5file.createTable()メソッドを使用して)、PyTablesの既存のテーブルにデータを挿入する方法についてはわかりません。チュートリアルでは、最初から作成されたPytTablesテーブルにデータを挿入する基本的なコードを示します。既存のpytablesテーブルにデータを追加する

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.このチュートリアルでは、既存のテーブルにデータを追加する方法について説明していますが、最初から作成されたテーブルを使用して、データを追加するための既存のテーブルを選択することについては基本的に考えていません。親切に助けてください。ありがとう。

答えて

11

追加モードでファイルを開く必要があります"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() 
+1

@khanこのソリューションで成功したことはありますか? –

+0

ありがとう@Mike、Python 3.5( 'xrange'ではなく' range'を使って)で完全に動作し、答えとしてマークする必要があります。グループとテーブルを作成するために、例を少し修正しました:https://gist.github.com/berezovskyi/10004d5fcf00a3d4477e – berezovskyi

関連する問題