File: conversions.py

package info (click to toggle)
python-petl 1.7.17-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,224 kB
  • sloc: python: 22,617; makefile: 109; xml: 9
file content (60 lines) | stat: -rw-r--r-- 1,753 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
from __future__ import division, print_function, absolute_import


# convert()
###########

import petl as etl
table1 = [['foo', 'bar', 'baz'],
          ['A', '2.4', 12],
          ['B', '5.7', 34],
          ['C', '1.2', 56]]
# using a built-in function:
table2 = etl.convert(table1, 'bar', float)
table2
# using a lambda function::
table3 = etl.convert(table1, 'baz', lambda v: v*2)
table3
# a method of the data value can also be invoked by passing
# the method name
table4 = etl.convert(table1, 'foo', 'lower')
table4
# arguments to the method invocation can also be given
table5 = etl.convert(table1, 'foo', 'replace', 'A', 'AA')
table5
# values can also be translated via a dictionary
table7 = etl.convert(table1, 'foo', {'A': 'Z', 'B': 'Y'})
table7
# the same conversion can be applied to multiple fields
table8 = etl.convert(table1, ('foo', 'bar', 'baz'), str)
table8
# multiple conversions can be specified at the same time
table9 = etl.convert(table1, {'foo': 'lower',
                              'bar': float,
                              'baz': lambda v: v * 2})
table9
# ...or alternatively via a list
table10 = etl.convert(table1, ['lower', float, lambda v: v*2])
table10
# conversion can be conditional
table11 = etl.convert(table1, 'baz', lambda v: v * 2,
                      where=lambda r: r.foo == 'B')
table11
# conversion can access other values from the same row
table12 = etl.convert(table1, 'baz',
                      lambda v, row: v * float(row.bar),
                      pass_row=True)
table12


# convertnumbers()
##################

import petl as etl
table1 = [['foo', 'bar', 'baz', 'quux'],
          ['1', '3.0', '9+3j', 'aaa'],
          ['2', '1.3', '7+2j', None]]
table2 = etl.convertnumbers(table1)
table2