Sort Power Table on Multiple Columns

Hi All,

Is it possible to sort a Power Table on multiple columns through scripting?
if yes, how?

Thanks in advance,
Cheers,

No, the dataset.sort only sorts on a single column.
I had this question last week and exchanged email with support.
Clearly the best answer would be to use SQL sort the data before it gets the client but, when that’s not an option…
Here’s an example of what works for me:

	# get a copy of the data in the Power Table
	editsToBeSaved = root.getComponent( 'Power Table' ).data
	# sort the data to be sure records are processed in the correct order - only sorts on one column but preserves prior order
	editsToBeSaved = system.dataset.sort( editsToBeSaved, 'task' )     	# last
	editsToBeSaved = system.dataset.sort( editsToBeSaved, 'operation' )	# 2nd
	editsToBeSaved = system.dataset.sort( editsToBeSaved, 'process' )  	# 1st
	# for row in range( editsToBeSaved.rowCount ):
		# do whatever needs to be done here

I am expecting (and so far, getting) the sort order of the prior sorts to be preserved.
The alternative would be to loop through the records and sort them yourself.

No way natively but you can use itemgetter and sort on multiple columns and then assign the dataset back to the table.

from operator import itemgetter
tbl = event.source.parent.getComponent('Power Table') #Get the table control
oDS = system.dataset.toPyDataSet(tbl.data) #Convert to a pyDataSet
hdrs=['Col1','Col2','Col3'] #The column names of the table
oDS = sorted(oDS, itemgetter(0,1,2)) #Sort the DS on the column numbers you want
tbl.data = system.dataset.toDataSet(hdrs,oDS) #Assign the new DS to the table

https://docs.python.org/3/library/operator.html#operator.itemgetter

3 Likes

Thanks for the answer. It’s really an interesting method.
I tried your code but it gave me the error:" TypeError: an integer is required at line oDS = sorted(oDS, itemgetter(0,1,2)) so after a little Google search it became oDS = sorted(oDS, key=itemgetter(1,4,8)).
Now it throws an error on the last line tbl.data = system.dataset.toDataSet(hdrs,oDS) which is java.lang.ClassCastException: class org.python.core.PyObjectDerived cannot be cast to class org.python.core.PySequence (org.python.core.PyObjectDerived and org.python.core.PySequence are in unnamed module of loader java.net.URLClassLoader @a3549b1)
I think it’s because oDS is a list of pyRow and the function system.dataset.toDataSet is expecting a list of lists.

Sounds like a job for ORDER BY in my view() expression function in Simulation Aids. You’d put your original binding on a custom property, then the view() expression on the data property. You can use a string property to hold the Pseudo-SQL and change it to change the ordering.