[AstroPy] astropy.table remove/delete row?

Aldcroft, Thomas aldcroft at head.cfa.harvard.edu
Wed Jun 26 08:46:17 EDT 2013


On Wed, Jun 26, 2013 at 8:05 AM, Brian Kloppenborg
<bkloppenborg at gmail.com>wrote:

>  Greetings,
>
> Today I noticed the astropy.table class (
> http://docs.astropy.org/en/latest/_generated/astropy.table.table.Table.html#astropy.table.table.Table)
> implements many functions for manipulating tables:
> add_column
> add_columns
> add_row
> remove_column
> remove_columns
>
> but it lacks similar functionality for row manipulation:
>
> add_rows - although this is easily accomplished by iteration
> remove_row
> remove_rows
>
> I could try manipulating the table._data structure directly, but because
> _data can be a numpy ndarray, dict, list or Table, it is not clear which
> method I should use without inspecting the data structure.
>
> I thought about slicing the table, but this would involve splitting then
> reassembling the table just to remove one row. I considered creating a
> mask, but this seems tedious (i.e. something that should be implemented
> via. a remove_row(s) function)
>
> Is a lack of a remove/delete_row(s) missing functionality or am I missing
> something obvious?
>

I think this is missing functionality and just opened a feature request
issue:
https://github.com/astropy/astropy/issues/1205

In the meantime there are some slightly nicer solutions for doing these
operations.  The current dev version of astropy the table package has a
vstack function that lets you stack tables together.  So something like the
following will work for add_rows, assuming you have a table named `dat` and
some `rows`:

>>> from astropy.table import vstack, Table
>>> dat = vstack(dat, Table(rows))

In this case the Table() initialization is taking care of converting any
valid inputs for `rows` into a nice table, and `vstack` is doing all the
logic to ensure that the columns match up, etc.  Note that at this time you
cannot directly initialize a Table from a list of row tuples.  This will
require some extra keyword arg in the initialization to distinguish a list
of rows from a list of columns, and we haven't settled on the best way yet.
 The way around this is:

>>> rows = [[1, 2.0, 'string'],  # list of rows
           [2, 3.0, 'values']]
>>> col_arr = zip(*rows)  # transpose to a list of columns
>>> t = Table(col_arr)

For removing rows you just need a couple of extra lines of code:

>>> mask = np.ones(len(dat), dtype=bool)
>>> mask[4] = False  # To remove one row
>>> mask[4:25] = False  # To remove a slice
>>> dat = dat[mask]

Cheers,
Tom


> Thanks,
> Brian
>
> _______________________________________________
> AstroPy mailing list
> AstroPy at scipy.org
> http://mail.scipy.org/mailman/listinfo/astropy
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/astropy/attachments/20130626/1f50702c/attachment.html>


More information about the AstroPy mailing list