Sorting columns of data by header name

TrustyTony

This does not look very efficient with transponation, sort and transponation back, so I am happy to hear about better alternatives.

249 Views
About the Author

IT Pro doing Eng-Fin-Eng translations

def sort_columns(table, **kwords):
	return list(zip(*sorted(zip(*table), **kwords)))

table = [
	['c', 'b', 'd', 'aa', 'ba', 'aab'],
	list(range(2,2+6)),
	list(range(6,6+6))]

for row in sort_columns(table): 
    print(row)
TrustyTony 888 pyMod Team Colleague Featured Poster

Here is alternative with rank order of headers for reading order of the rows:

from __future__ import print_function

table = [
    ['c', 'b', 'd', 'aa', 'ba', 'aab'],
    list(range(2,2+6)),
    list(range(6,6+6))]

ranks = sorted(zip(table[0], range(len(table[0]))))
ranks= dict((r, ind) for r, (header, ind) in enumerate(ranks))
m = max(len(str(item)) for row in table  for item in row)
for row in table:
    for key in range(len(row)):
        print (' %*s' % (m, row[ranks[key]]), end=',')
    print()
TrustyTony 888 pyMod Team Colleague Featured Poster

You can save the rank order in old table by slice assignment from generator:

for rowno,row in enumerate(table):
    table[rowno][:] = (row[ranks[ind]] for ind in range(len(ranks)))

print(table)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.