table1 = [['foo', 'bar'], ['M', 12], ['F', 34], ['-', 56]] from petl import addfield, look look(table1) # using a fixed value table2 = addfield(table1, 'baz', 42) look(table2) # calculating the value table2 = addfield(table1, 'baz', lambda rec: rec['bar'] * 2) look(table2) # an expression string can also be used via expr from petl import expr table3 = addfield(table1, 'baz', expr('{bar} * 2')) look(table3) # rowslice table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['c', 5], ['d', 7], ['f', 42]] from petl import rowslice, look look(table1) table2 = rowslice(table1, 2)
table1 = [['foo', 'bar'], ['M', 12], ['F', 34], ['-', 56]] from petl import extend, look look(table1) # using a fixed value table2 = extend(table1, 'baz', 42) look(table2) # calculating the value table2 = extend(table1, 'baz', lambda rec: rec['bar'] * 2) look(table2) # an expression string can also be used via expr from petl import expr table3 = extend(table1, 'baz', expr('{bar} * 2')) look(table3) # rowslice table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['c', 5], ['d', 7], ['f', 42]] from petl import rowslice, look look(table1) table2 = rowslice(table1, 2)
table1 = [['foo', 'bar'], ['M', 12], ['F', 34], ['-', 56]] from petl import extend, look look(table1) # using a fixed value table2 = extend(table1, 'baz', 42) look(table2) # calculating the value table2 = extend(table1, 'baz', lambda rec: rec['bar'] * 2) look(table2) # an expression string can also be used via expr from petl import expr table3 = extend(table1, 'baz', expr('{bar} * 2')) look(table3) # rowslice table1 = [['foo', 'bar'], ['a', 1], ['b', 2], ['c', 5], ['d', 7], ['f', 42]] from petl import rowslice, look look(table1) table2 = rowslice(table1, 2) look(table2) table3 = rowslice(table1, 1, 4) look(table3) table4 = rowslice(table1, 0, 5, 2) look(table4)
def addfield(data, source, field, value): """Return the first n rows of the data table and store them in the destination data table.""" s = data.get(source) s = s.addfield(field, petl.expr(value)) data.set(source, s)