File: add-column.py

package info (click to toggle)
pytables 3.10.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,228 kB
  • sloc: ansic: 82,212; python: 65,296; cpp: 753; sh: 394; makefile: 100
file content (77 lines) | stat: -rw-r--r-- 2,076 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"Example showing how to add a column on a existing column"

import tables as tb


class Particle(tb.IsDescription):
    name = tb.StringCol(16, pos=1)  # 16-character String
    lati = tb.Int32Col(pos=2)  # integer
    longi = tb.Int32Col(pos=3)  # integer
    pressure = tb.Float32Col(pos=4)  # float  (single-precision)
    temperature = tb.Float64Col(pos=5)  # double (double-precision)


# Open a file in "w"rite mode
fileh = tb.open_file("add-column.h5", mode="w")
# Create a new group
group = fileh.create_group(fileh.root, "newgroup")

# Create a new table in newgroup group
table = fileh.create_table(group, "table", Particle, "A table", tb.Filters(1))

# Append several rows
table.append(
    [
        ("Particle:     10", 10, 0, 10 * 10, 10**2),
        ("Particle:     11", 11, -1, 11 * 11, 11**2),
        ("Particle:     12", 12, -2, 12 * 12, 12**2),
    ]
)

print("Contents of the original table:", fileh.root.newgroup.table[:])

# close the file
fileh.close()

# Open it again in append mode
fileh = tb.open_file("add-column.h5", "a")
group = fileh.root.newgroup
table = group.table

# Get a description of table in dictionary format
descr = table.description._v_colobjects
descr2 = descr.copy()

# Add a column to description
descr2["hot"] = tb.BoolCol(dflt=False)

# Create a new table with the new description
table2 = fileh.create_table(group, "table2", descr2, "A table", tb.Filters(1))

# Copy the user attributes
table.attrs._f_copy(table2)

# Fill the rows of new table with default values
for i in range(table.nrows):
    table2.row.append()
# Flush the rows to disk
table2.flush()

# Copy the columns of source table to destination
for col in descr:
    getattr(table2.cols, col)[:] = getattr(table.cols, col)[:]

# Fill the new column
table2.cols.hot[:] = [row["temperature"] > 11**2 for row in table]

# Remove the original table
table.remove()

# Move table2 to table
table2.move("/newgroup", "table")

# Print the new table
print("Contents of the table with column added:", fileh.root.newgroup.table[:])

# Finally, close the file
fileh.close()