Skip to content

Instantly share code, notes, and snippets.

@AngelBerihuete
Forked from PBarmby/tab_trans.py
Created June 1, 2016 12:25
Show Gist options
  • Save AngelBerihuete/31999a8bd371b45a888ce757275455db to your computer and use it in GitHub Desktop.
Save AngelBerihuete/31999a8bd371b45a888ce757275455db to your computer and use it in GitHub Desktop.
Transpose tables in astropy
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