Created
May 1, 2014 15:09
-
-
Save PBarmby/61c6addda169568f4a0d to your computer and use it in GitHub Desktop.
Transpose tables in astropy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from astropy.table import Table, Column | |
def transpose_table(tab_before, id_col_name='ID'): | |
'''Returns a copy of tab_before (an astropy.Table) with rows and columns interchanged | |
id_col_name: name for optional ID column corresponding to | |
the column names of tab_before''' | |
# contents of the first column of the old table provide column names for the new table | |
# TBD: check for duplicates in new_colnames & resolve | |
new_colnames=tuple(tab_before[tab_before.colnames[0]]) | |
# remaining columns of old table are row IDs for new table | |
new_rownames=tab_before.colnames[1:] | |
# make a new, empty table | |
tab_after=Table(names=new_colnames) | |
# add the columns of the old table as rows of the new table | |
for r in new_rownames: | |
tab_after.add_row(tab_before[r]) | |
if id_col_name != '': | |
# add the column headers of the old table as the id column of new table | |
tab_after.add_column(Column(new_rownames, name=id_col_name),index=0) | |
return(tab_after) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment