Author: Hans Terlouw <gipsy@astro.rug.nl>
Module tabarray provides a class which allows the user to read, write and manipulate simple table-like structures. It is based on NumPy and the table-reading part has been optimized for speed. When the flexibility of SciPy’s read_array() function is not needed, Tabarray can be considered as an alternative.
Tabarray is a subclass of NumPy’s ndarray. It provides all of ndarray’s functionality as well as some extra methods and attributes.
Parameters: |
|
---|---|
Raises: | IOError, when the file cannot be opened. IndexError, when a line with an inconsistent number of fields is encountered in the input file. ValueError: when a field cannot be decoded as a number and no alternative value was specified. |
Attributes:
the number of rows
the number of columns
a list with slice objects which can be used to address the different segments from the table. Segments are parts of the table which are separated by comment blocks which meet the conditions specified by argument segsep. The following example illustrates how a program can iterate over all segments:
1 2 3 4 5 6 | from kapteyn.tabarray import tabarray
coasts = tabarray('world.txt')
for segment in coasts.segments:
coast = coasts[segment]
|
Methods:
Parameters: | cols – a tuple or list with the numbers (zero-relative) of the columns to be extracted. |
---|---|
Returns: | a NumPy array. |
Extract specified columns from a tabarray and return an array containing these columns. Cols is a tuple or list with the column numbers. As the first index of the resulting array is the column number, multiple assignment is possible. E.g., x,y = t.columns((2,3)) delivers columns 2 and 3 in variables x and y. Default: return all columns.
Parameters: | rows – a tuple or list containing the numbers (zero-relative) of the rows to be extracted. |
---|---|
Returns: | a new tabarray. |
This method extracts specified rows from a tabarray and returns a new tabarray. Rows is a tuple or list containing the row numbers to be extracted. Normal Python indexing applies, so (0, -1) specifies the first and the last row. Default: return whole tabarray.
Write the contents of a tabarray to a file.
Parameters: |
|
---|
TableIO-compatible function for directly extracting table data from a file.
Parameters: |
|
---|
TableIO-compatible function for directly writing table data to a file.
Parameters: |
|
---|
Suppose you have a file with catheti data from right-angled triangles and you want to compute the hypotenuses and write the result to a second file. The input file may be as follows:
# Triangle data
#
3.0 4.0 ! classic example
4.1 3.6
10.0 10.0
Then the following simple script will do the job:
#!/usr/bin/env python
import numpy
from kapteyn.tabarray import tabarray
x,y = tabarray('triangles.txt').columns()
tabarray([x,y,numpy.sqrt(x*x+y*y)]).writeto('outfile.txt')
leaving the following result in the output file:
3 4 5
4.1 3.6 5.45619
10 10 14.1421