recio – read/write tabular data from/to NumPy record arrays

Read/write tabular data to/from NumPy record arrays. Alpack tables, csv and excel formats are supported.

A table has three components:

  1. heading - Initial lines starting with a hash (#), not including

    the header (only supported with Alpack tables).

  2. header - The last initial line starting with a hash (#).

  3. data - The lines following the header. A blank line or a line

    starting with a hash (#) ends the The data section.

Example of a Alpack table:

# This is a heading...
#
# time(s)   T(C)        Css  PZ(Pa)
      0.0  330.0  0.0053138     0.0
      1.0  330.0  0.0053138     0.0
      5.0  330.0  0.0053138     0.0
     10.0  330.0  0.0053138     0.0
pario.recio.escaped_split(s, sep, escape='\\', keep=True, quote=None, endquote=None, maxsplit=None)[source]

Splits a string considering escape characters and quotes.

Parameters :

s : string

String to split.

sep : string

Separator to split the string at unless preceeded by an escape character.

escape : None | string

Escape character. Preceeding sep or a quote with the escape character will make them loose their special meaning.

keep : bool

Whether to keep interpreated escape characters in the output. Interpreated escape characters are those preceeding sep, a quote or an escape character.

quote : None | string

Quote characters. Quotes starts with a quote character and ends the same character, unless it is escaped or endquote is given. In the latter case the character with the same index in endquote as the starting quote character has in quote ends the quote.

endquote : None | string

Characters ending a quote. It must either be None or have the same length as quote.

maxsplit | None | int

If given, at most maxsplit splits are done.

Examples

>>> escaped_split(r'a\:\=b=c', '=')
['a\\:\\=b', 'c']
>>> escaped_split(r'a\:\=b=c', '=', keep=False)
['a\\:=b', 'c']
>>> escaped_split(r'a\:\=b=cd', '=')
['a\\:\\=b', 'cd']
>>> escaped_split(r'a\:\=b=cd', '=', keep=False)
['a\\:=b', 'cd']
>>> escaped_split('col1[col2=u]:opt=v', '=', quote='[', endquote=']')
['col1[col2=u]:opt', 'v']
pario.recio.excel2rec(filename, sheetname=None, startcell='A1', endcell=None, has_header=True, names=None, dtype=None, formats=None, titles=None)[source]

Reads a record array from a Excel document.

Parameters :

filename: string

Name of the Excel document.

sheetname: None | string

Name of sheet to read. Defaults to the first sheet.

startcell: string

Upper left cell of the table to read.

endcell: None | string

Bottom right cell of the table to read. If None, all available rows and colums will be read.

has_header: bool

Whether the first row is a header. If True, column names will be read form here when names is not given.

names: None | sequence of strings | comma-separated string

Field names. By default they are read from the header, when has_header is True.

dtype: dtype instance

dtype of return.

formats: None | sequence of strings

Column formats.

titles: None | sequence of strings | comma-separated string

Record array titles. This defaults to names with paranthesis stripped off (for names without paranthesis and empty paranthesis is appended).

pario.recio.excel_cell2tuple(cell)[source]

Returns (row, col) tuple given a cell id.

Examples

>>> excel_cell2tuple('B1')
(0, 1)
pario.recio.excel_column2string(n)[source]

Returns column number n as string.

Examples

>>> excel_column2string(0)
'A'
>>> excel_column2string(26)
'AA'
pario.recio.excel_string2column(s)[source]

Returns column label s as number.

Examples

>>> excel_string2column('A')
0
>>> excel_string2column('AA')
26
pario.recio.excel_tuple2cell(t)[source]

Returns cell id given (row, col) tuple.

Examples

>>> excel_tuple2cell((0, 1))
'B1'
pario.recio.get_formats(reading)[source]

Returns all available filters. Input formats are returned if reading is true, otherwise output formats are returned.

pario.recio.getcol(rec, col, unit=None, first_field=0)[source]

Returns column col from record array rec, where col is a field name, title or number (counting from first_field). If unit is given, the output will be converted to this unit.

pario.recio.getdata(filename, colname, index=None, unit=None, **kwargs)[source]

Returns the given column from filename. If index is given, it must be a valid NumPy index, or a string representation of it. kwargs are passed on to read(). **kwargs is passed on to read().

pario.recio.guess_format(filename, fmt=None, fallback='txt')

Returns guessed format based on fmt or filename. If no format can be determined fallback is returned.

pario.recio.lookup(name)

Looks up name in the local, global or builtin scopes in turns, returning it’s value in the scope where it is first found.

pario.recio.parse_heading(lines, lineno=0, comment='#', maxheads=None, converters=None)

Parsing heading and extract description, tags, fieldheads.

Parameters :

lines : sequence | string | bytes

The heading to parse, provided either as a sequence of lines to parse or a string.

lineno : int

Line number of the first line. Used for error reporting.

comment : string

A comment character that all lines belonging to the heading must start with this string.

maxheads : None | int

Max number of field heads to return.

converters : None | sequence | string

A sequence of converter function objects or function names (looked up in the local, global or builtin scopes, in this order) passed to typeconvert() to convert values to correct type. converters may also be given as a comma-separated string.

Returns :

tags : dict

A dict with tag name-value pairs.

fieldheads : list

A list of lists with header tokens.

lineno : int

Line number of the final line.

Notes

A heading is an initial set of lines before the acual data starting with the comment character/string. It may contain:

  • description - running text describing the data. This is returned as tags['description']. Non-special lines that are not tags or fieldheads are identified are description lines.

  • tags - a more formal description of the data with tag names and associated values. Tag lines are indented and of the form:

    key :: value
  • fieldheads - are the last lines in the heading containing the same number of tokens as the number of fields/columns in the following data. Normally it is just the header, but it might span several lines. A good practice is to leave a blank line (except for the initial comment) before the fieldheads to avoid that the line above unintended is treated as a fieldhead.

pario.recio.read(filename, fmt=None, lang=None, names=None, dtype=None, formats=None, titles=None, **kwargs)[source]

Reads filename and return a NumPy record array.

Parameters :

filename : string

File to read.

fmt : None | ‘csv’ | ‘xls’ | ‘txt’

File format. Valid values are:
  • None - fmt is taken from the file extension.
  • ‘csv’ - use matplotlib.mlab.csv2rec(). Requires matplotlib.
  • ‘xls’ - use excel2rec(). Requires xlrd.
  • otherwise use string2rec(), assumed an Alpack table.

names : None | sequence of strings | comma-separated string

Field names. By default they are read from the header (last non- comment line preceeding the data).

lang : None | string

Read localized csv input. In addition to the platform-specifig country-codes, lang may also be one of: “C”, “american”, “danish”, “english”, “french”, “german”, “norwegian” or “swedish”.

dtype : dtype instance

dtype of return.

formats : None | sequence of strings

NumPy formats describing the column types.

titles : None | sequence of strings | comma-separated string

Record array titles. This defaults to names with paranthesis stripped off (for names without paranthesis and empty paranthesis is appended).

kwargs :

Keyword arguments are passed to the reader.

pario.recio.readdata(filespec, cwd='.')[source]

Reads data from files and return it as a list of 1d numpy arrays.

filespec is a comma-separated list of one or more file names, followed by a colon-separated list of colum names and option-value pairs.

If the filename are relative, they will be relative to the directory cwd.

The grammar for filespec can formally be written as:

filespec   ::= filename (":" columnspec | ":" option)* ["," filespec]
columnspec ::= column_id [ "[" indexspec "]" ] 
option     ::= name "=" value
indexspec  ::= integer | slice | column_id "=" val ("," val)*
column_id  ::= integer | string

Comma, colon, equal and backslash characters can be backslash-escaped.

Columns can be specified either by name or by number and optionally followed by a pair of bracket ([]) supporting standard indexing.

If your data file has columns ‘year’ and ‘population’ it is also possible to write population[year=2012,2014]. This will return the population at 2012 and 2014 using linearly interpolation. The column ‘year’ must be increasing. The options left and right (described below) are used if a specified year is outside the range of the data.

The name=value options are passed to recio.read() as keyword arguments to the reader. However, a few options are interpreated by readdata() and not passed further.

Options interpreated by readdata()
first_column : int
Index of the first column when column are specified as inter. The default is zero.
left : None | float
Value to return if val is smaller than the data.
right : None | float
Value to return if val is larger than the data.

Notes

This function uses eval() for the bracket indexing, which might be a security risk if filespec comes from an untrusted user.

Examples

Read ‘col1’ and ‘col2’ from ‘filename’ and return them:

filename:col1:col2

Read ‘col1’ and ‘col2’ from both ‘file1’ and ‘file2’ (returning four columns) and pass opt=val as keyword argument to recio.read() when reading the files:

file1,file2:col1:col2:opt=val

Read 3 columns, two from file1 and one from ‘file2’, passing opt1=val1 and opt2=val2 to recio.read():

file1:col1:col2:opt1=val1:opt2=val2,file2:col3

Read element 1 to 10 from column ‘col’ in ‘file’:

file:col[1:10]

Read the columns ‘year’ and ‘population’ from ‘population.txt’ and return interpolated population at 2012 and 2014:

population.txt:population[year=2012,2014]
class pario.recio.rec

A subclass of np.recarray containing most of the I/O features provided with this module in addition to:

  • field units
  • field heads, i.e.
  • tags
Parameters :

array: array_like

Any object that can be converted into a numpy record array.

dtype : data-type

The desired data-type. By default, the data-type is determined from names, titles, units, formats, aligned and byteorder.

names: None | sequence of strings | string

Column names. Given either a sequence of column names or as a comma-separated string.

units: bool | sequence of strings | string

Whether to include units in names and titles. If true, the elements of names and titles will be set from names according to the following table:

names -> names titles
name(unit) -> name(unit) name
name() -> name name()
name -> name name()

where the units (optional) are included in parenthesis following the column names in names. Hence, setting units to anything other than false, will override titles.

If units are explicitly specified as a sequence of strings or a comma-separated string, any unit-part of names will be overridden.

titles: None | sequence of strings | string

Column titles. Given either a sequence of column titles or as a comma-separated string.

tags : None | mapping | string

Tags associated with this rec object. Can be a mapping or a comma-separated string of key=value pairs.

fieldheads : None | sequence

A nested sequence of additional field heads. It might also be given as a sequence of comma-separated strings.

formats : list of data-types

A list containing the data-types for the different columns, e.g. ['i4', 'f8', 'i4']. formats does not support the new convention of using types directly, i.e. (int, float, int). Note that formats must be a list, not a tuple. Given that formats is somewhat limited, we recommend specifying dtype instead.

aligned : bool

Align the fields in memory as the C-compiler would.

byteorder : {‘<’, ‘>’, ‘=’}

Byte-order for all fields.

copy : bool

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

Examples

>>> rec([(u'a', 1, 1.1), ('b', 2, 2.2)], units=False)  
rec([(u'a', 1, 1.1), (u'b', 2, 2.2)], 
      dtype=[('f0', '<U4'), ('f1', '<i8'), ('f2', '<f8')])
append_fields(arrs, names=None, formats=None, units=None, fieldheads=None)

Returns a new rec object with arrays arrs appended as new fields.

Note that arrs must be a sequence, even if only a single field is appended.

The arguments names, formats, and units applies to the new fields. They can be provided as squences or as comma- separated strings.

fieldheads is a sequence of field heads for each array in arrs. Note that this implies that fieldheads is transposed, compared to fieldheads property.

asrec()

Returns a view as a numpy record array.

drop_fields(names, first_field=0)

Returns a view of self with the named fields dropped.

edit(**kw)

Opens a graphical window for editing values.

This is a convenient wrapper around arrayedit.arrayedit() with wait set to true. Refer to this function for a description of arguments and return value.

fieldheads

Direct access to list of fieldheads.

classmethod fromfile(filename, fmt=None, **kw)

Reads filename from file and returns a rec instance.

This is a convenient wrapper around read(). Refer to this function for a description of the arguments.

classmethod fromstring(lines, **kw)

Parses lines and returns a rec instance.

This is a convenient wrapper around string2rec(). Refer to this function for a description of the arguments.

insert_fieldhead(fieldhead, index='end')

Insert a new field head to the list of field heads (before index).

fieldhead must be a sequence of the same length as the number of fields. If index is “end”, the new field head is appended.

labels

Field labels.

names

Field names.

tags

Direct access to tags dictionary.

tofile(filename, fmt=None, **kw)

Writes self to filename.

This is a convenient wrapper around write(). Refer to this function for a description of the arguments.

tostring(**kw)

Returns self as string.

This is a convenient wrapper around rec2string(). Refer to this function for a description of arguments and return value.

units

Field units.

view_fields(names, first_field=0)

Returns a view of self with only the named fields.

pario.recio.rec2html(rec, indent=0, columns=None, formatters=None, tableclass=None, rowclasses=None, columnclasses=None, linesep='\n')[source]

Formats a numpy records array as a html table

Column labels can be grouped together by prefixing a set of adjacent labels with the same prefix followed by colon.

Parameters :

rec: record array

Record array to convert.

indent: int

Indentation of the output.

columns: None | sequence

Sequence of field names or (field_name, column_label) pairs to include in the output, where column_label defaults to the field_name. If columns is not given, it defaults to rec.dtype.names.

formatters: None | str | callable | dict

A format string, callable or a dict mapping field names to strings or callables. Callables takes the value as the only argument and returns it as a formatted string. If formatters is a dict and None is a key, will its value be used as default when the field name matches not other keys.

tableclass: None | str

css class for the <table> tag.

rowclasses: None | sequence of strings

css classes for each <tr> tag. The length or rowclasses must equal length or rec.

columnclasses: None | sequence of strings

css classes for each <td> tag. The length or columnclasses must equal number of columns.

linesep: str

Line separator.

Examples

>>> import numpy as np
>>> rec = np.rec.fromarrays([(1, 2, 3), ('a', 'b', 'c'), (1.2, 2.3, 4.3)], 
...                         names=('i', 's', 'f'))
>>> columns = [('s', 'string'), ('i', 'number:int'), ('f', 'number:float')]
>>> print(rec2html(rec, columns=columns))
<table>
  <tr>
  <th rowspan="2">string</th>
  <th colspan="2">number</th>

  </tr>
  <tr>

  <th>int</th>
  <th>float</th>
  </tr>
  <tr>
    <td>a</td>
    <td>1</td>
    <td>1.2</td>
  </tr>
  <tr>
    <td>b</td>
    <td>2</td>
    <td>2.3</td>
  </tr>
  <tr>
    <td>c</td>
    <td>3</td>
    <td>4.3</td>
  </tr>
</table>
pario.recio.rec2string(rec, heading=None, header=None, sep=' ', linesep=None, comment='# ', alignments=None, precisions=None, types=None)[source]

Convert record array rec to a string.

Parameters :

heading : None | sequence of strings

A heading to at the top of the table.

header : None | sequence of strings | comma-separated string | nested seq

If given, alternative header. Multiline headers are also supported (see the fieldheads return value of parse_heading()).

sep : string

Column separator.

linesep : None | string

Line separator. If not given it defaults to the line separator of the operating system.

comment : string

A string to prepend each line in heading.

alignments : None | string | sequence of strings

Alignment of columns. If string, it can either be a single character applied to all columns or a comma-separated string of alignment characters for each column. Must be one of:

‘<’:left-aligned
‘>’:right-aligned
‘=’:padding between sign number (only numeric types)
‘^’:centered

precisions : None | int | sequence of None/int

Precision of numeric types.

types : None | string | sequence of strings

Type specification character for each column. If string, it can either be a single character applied to all columns or a comma-separated string of type characters for each column. Valid type characters are:

string:‘s’, None
integer:‘b’, ‘c’, ‘d’, ‘o’, ‘x’, ‘X’, ‘n’, None
float:‘e’, ‘E’, ‘f’, ‘F’, ‘g’, ‘G’, ‘n’, ‘%’, None

Notes

See https://docs.python.org/2/library/string.html#format-specification-mini-language for more information about the type characters.

pario.recio.rec_append_fields(rec, arrs, names=None, formats=None, titles=None)

Returns a new record array with the arrays in arrs appended as new fields. The arguments names, formats, and titles applies to the new fields. They can be provided as squences or as comma-separated strings.

If rec has titles, default titles will the initial part of name up to the first left paranthesis if name contains a left paranthesis, otherwise name with “()” appended to it.

pario.recio.rec_convert_names(rec, names, first_field=0)[source]

Returns a list with names converted to proper field names of rec. names may be a sequence or a comma-separated string with field names, titles or field numbers. first_field is the number of the first field.

pario.recio.rec_default_titles(rec)[source]

Returns a list titles. Unset titles will be: LABEL if name is “LABEL(UNIT)” [i.e. name contains ‘(‘] LABEL() if name is “LABEL” [i.e. name doesn’t contains ‘(‘]

pario.recio.rec_drop_fields(rec, names, first_field=0)

Returns a view of self with the named fields dropped.

pario.recio.rec_formats(rec)

Returns a list of field formats.

pario.recio.rec_getindex(rec, col, first_field=0)[source]

Returns the index of the given column, where col is a field name, title or number (counting from first_field).

pario.recio.rec_getlabel(rec, col, first_field=0)[source]

Returns the label of the given column, where col is a field name, title or number (counting from first_field).

pario.recio.rec_getname(rec, col, first_field=0)[source]

Returns the name of the given column, where col is a field name, title or number (counting from first_field).

pario.recio.rec_gettitle(rec, col, first_field=0)[source]

Returns the title of the given column, where col is a field name, title or number (counting from first_field).

pario.recio.rec_getunit(rec, col, first_field=0)[source]

Returns the label of the given column, where col is a field name, title or number (counting from first_field). An enpty string is returned if the column has no unit.

pario.recio.rec_has_titles(rec)

Returns true if record array rec has titles, otherwise false.

pario.recio.rec_index(rec, name)[source]

Returns the index of the given column name.

pario.recio.rec_insert_field(rec, index, arr, name=None, format=None, title=None, offset=None)

Returns a view of rec with arr inserted before position index. The arguments name, format, title and offset applies to the new fields.

If rec has titles, default titles will the initial part of name up to the first left paranthesis if name contains a left paranthesis, otherwise name with “()” appended to it.

pario.recio.rec_keep_fields(rec, names, first_field=0)[source]

Returns a view of rec with only the named fields.

pario.recio.rec_labels(rec)[source]

Returns a list of field labels (names without the unit part).

pario.recio.rec_names(rec)

Returns a list of field names.

pario.recio.rec_offsets(rec)

Returns a list of field offsets.

pario.recio.rec_setname(rec, col, value, first_field=0)[source]

Sets the name of the given column to value, where col is a field name, title or number (counting from first_field).

NOTE that this function does not change the titles. Hence:

rec_setlabel(rec, 0, 'length(m)')

will not make “length” an alias for the first column.’

pario.recio.rec_setunit(rec, col, value, first_field=0)[source]

Sets the name of the given column to value, where col is a field name, title or number (counting from first_field).

pario.recio.rec_titles(rec)[source]

Returns a list of titles. None is placed for unset titles.

pario.recio.rec_units(rec)[source]

Returns a list of column units (parts of the field name enclosed in parenthisis). An empty string is returned for fields without unit.

pario.recio.setcol(rec, col, value, unit=None, first_field=0)[source]

Sets column col in record array rec to value, where col is a field name, title or number (counting from first_field). unit is the unit of value. If given, value will first be converted to the unit of the given column.

pario.recio.setdata(filename, colname, value, index=None, unit=None, **kwargs)[source]

Sets the given column in filename to value. If index is given, it must be a valid NumPy index, or a string representation of it. **kwargs is passed on to read().

pario.recio.split_label(label)[source]

Splits label into a name and unit-part, where unit is optional. If unit is included, it follows name and is enclosed in parentheses.

Examples

>>> split_label('length')
('length', '')
>>> split_label('length(m)')
('length', 'm')
pario.recio.string2bool(value)

Converts the string value to bool and returns the result. Valid strings are:

'TRUE', 'True', 'true', 'YES', 'Yes', 'yes', '.TRUE.', '.true.'

or:

'FALSE', 'False', 'false', 'NO', 'No', 'no', '.FALSE.', '.false.'
pario.recio.string2rec(lines, lineno=0, names=None, dtype=None, formats=None, titles=None, converters=None, maxfields=None, maxheads=None, comment='#', section_separator=None, section=0, full_output=False)[source]

Parse a table given in lines and return a record array.

Parameters :

lines : string | sequence of strings

Lines to parse.

lineno : int

Line number of the first line. Used for error reporting.

names : None | sequence of strings | comma-separated string

Field names. By default they are read from the header (last non- comment line preceeding the data).

dtype : dtype instance

dtype of return.

formats : None | sequence of strings

Column formats.

titles : None | sequence of strings | comma-separated string

Record array titles. This defaults to names with paranthesis stripped off (for names without paranthesis and empty paranthesis is appended).

converters : None | sequence | string

A sequence of converter function objects or function names (looked up in the local, global or builtin scopes, in this order) passed to typeconvert() to convert values to correct type. converters may also be given as a comma-separated string.

maxfields : None | int

Max number of fields in returned record array. In case some lines in lines has more words than maxfields, the last field will be a string containing the remaining of the line. Zero means that no maximum is imposed.

maxheads : None | int

Max number of field heads to return.

comment : string

A comment character that all lines belonging to the heading must start with this string.

section_separator : None | string

Section separator. If None, no section separation is done. Otherwise section_separator should be a regular expression matching lines separating sections. E.g. to separate sections with blank lines, you can use section_separator=r'^\s*$'.

section : int | slice

The section(s) to parse when section_separator is not None. The first section starts on line number lineno.

full_output : bool

If true, tags, fieldheads and lineno are also returned. See Returns below.

Returns :

rec : record array

The record array.

tags : dict (optional)

A dict with tag name-value pairs.

fieldheads : list (optional)

A list of lists with header tokens.

lineno : int (optional)

Line number of the final line parsed.

pario.recio.torecord(array, dtype=None, names=None, units=False, titles=None, formats=None, aligned=None, byteorder=None, copy=None)[source]

Converts array to a numpy record array.

Parameters :

array: array_like

Any object that can be converted into a numpy record array.

dtype : data-type

The desired data-type. By default, the data-type is determined from names, titles, units, formats, aligned and byteorder.

names: None | sequence of strings | string

Column names. Given either a sequence of column names or as a comma-separated string.

units: bool | sequence of strings | string

Whether to include units in names and titles. If true, the elements of names and titles will be set from names according to the following table:

names -> names titles
name(unit) -> name(unit) name
name() -> name name()
name -> name name()

where the units (optional) are included in parenthesis following the column names in names. Hence, setting units to anything other than false, will override titles as well as any ending parenthesis in names.

If units are explicitly specified as a sequence of strings or a comma-separated string, any unit-part of names will be overridden.

titles: None | sequence of strings | string

Column titles. Given either a sequence of column titles or as a comma-separated string. Only used when units is not given.

formats : list of data-types

A list containing the data-types for the different columns, e.g. ['i4', 'f8', 'i4']. formats does not support the new convention of using types directly, i.e. (int, float, int). Note that formats must be a list, not a tuple. Given that formats is somewhat limited, we recommend specifying dtype instead.

aligned : bool

Align the fields in memory as the C-compiler would.

byteorder : {‘<’, ‘>’, ‘=’}

Byte-order for all fields.

copy : bool

If true (default), then the object is copied. Otherwise, a copy will only be made if __array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).

Examples

>>> a = [(0., 0), (1., 1), (2., 4)]
>>> rec1 = torecord(a, names='time(s),number')
>>> rec1
rec.array([(0.0, 0), (1.0, 1), (2.0, 4)], 
      dtype=[('time(s)', '<f8'), ('number', '<i8')])
>>> rec1['time']   
Traceback (most recent call last):
    ...
ValueError: field named time not found...
>>> rec2 = torecord(a, names='time(s),number', units=True)
>>> rec2
rec.array([(0.0, 0), (1.0, 1), (2.0, 4)], 
      dtype=[(('time', 'time(s)'), '<f8'), (('number()', 'number'), '<i8')])
>>> rec2['time']
array([ 0.,  1.,  2.])
pario.recio.typeconvert(value, converters=None)

Tries to convert value to another type using the converters in the sequence converters. converters may also be a comma-separated string of converter names (looked up in the local, global or builtin scopes).

The new value after the first successful convertsion is returned.

If value is a sequence, a list is returned with all elements converted using the first conversion that works for all of them.

If types is None, it defaults to (int, float, ast.literal_eval, string2bool, str).

Examples

>>> typeconvert('3.4')
3.4
>>> typeconvert('3.4a')
'3.4a'
>>> typeconvert('yes')
True
>>> typeconvert('yes', converters='int,float,string2bool')
True
>>> typeconvert(['3', '1', '2.2'])
[3.0, 1.0, 2.2]
>>> typeconvert([3, 1, 2.2])    # Note that 2.2 is truncated!
[3, 1, 2]
>>> typeconvert(['a', 1, 2.2])
['a', '1', '2.2']
pario.recio.write(filename, rec, fmt=None, lang=None, **kwargs)[source]

Write NumPy record array rec to filename.

Parameters :

filename : string

Name of file to write.

rec : record array

Record array to write.

fmt : None | ‘csv’ | ‘xls’ | ‘txt’

File format. Valid values are:
  • None - fmt is taken from the file extension.
  • ‘csv’- use matplotlib.mlab.rec2csv(). Requires matplotlib.
  • ‘xls’- use rec2excel(). Requires xlrd.
  • otherwise use rec2string(), assuming an Alpack table.

lang : None | string

Read localized csv input. In addition to the platform-specifig country-codes, lang may also be one of: “C”, “american”, “danish”, “english”, “french”, “german”, “norwegian” or “swedish”.

kwargs :

Keyword arguments are passed to the writer.

pario.recio.lookup(name)

Looks up name in the local, global or builtin scopes in turns, returning it’s value in the scope where it is first found.

pario.recio.string2bool(value)

Converts the string value to bool and returns the result. Valid strings are:

'TRUE', 'True', 'true', 'YES', 'Yes', 'yes', '.TRUE.', '.true.'

or:

'FALSE', 'False', 'false', 'NO', 'No', 'no', '.FALSE.', '.false.'
pario.recio.typeconvert(value, converters=None)

Tries to convert value to another type using the converters in the sequence converters. converters may also be a comma-separated string of converter names (looked up in the local, global or builtin scopes).

The new value after the first successful convertsion is returned.

If value is a sequence, a list is returned with all elements converted using the first conversion that works for all of them.

If types is None, it defaults to (int, float, ast.literal_eval, string2bool, str).

Examples

>>> typeconvert('3.4')
3.4
>>> typeconvert('3.4a')
'3.4a'
>>> typeconvert('yes')
True
>>> typeconvert('yes', converters='int,float,string2bool')
True
>>> typeconvert(['3', '1', '2.2'])
[3.0, 1.0, 2.2]
>>> typeconvert([3, 1, 2.2])    # Note that 2.2 is truncated!
[3, 1, 2]
>>> typeconvert(['a', 1, 2.2])
['a', '1', '2.2']

Previous topic

parameters - encapsulates model parameters

Next topic

variables – track model variables through execution

This Page