Boosted_d16 Boosted_d16 - 1 month ago 5
Python Question

Exclude given columns when sorting a table python

I am trying to sort a table but would like to exclude given columns by their names while sorting. In other words, the given columns should remain where they were before sorting. This is aimed at dealing with columns like "Don't know', "NA" etc.

The API I'm using is unique and company specific but it uses python.

A table in this API is an object which is a list of rows, where each row is a list of cells and each cell is a list of cell values.

I am currently have a working function which sorts a table but I would like to edit/modify this to exclude a given column by it's name but I am struggling to find a way.

FYI - "Matrix" can be thought of as the table itself.

def SortColumns(byRow=0, usingCellValue=0, descending=True):
"""
:param byRow: Use the values in this row to determine the sort order of the
columns.
:param usingCellValue: When there are multiple values within a cell use this
to control which value row within each cell is used for sorting
(zero-based)
:param descending: Determines the order in which the values should be
sorted.
"""

for A in range(0,Matrix.Count):
for B in range(0,Matrix.Count):
if(A==B):
continue; #do not compare rows against eachother

valA = Matrix[byRow][A][usingCellValue].NumericValue if Matrix[byRow][A].Count > usingCellValue else None;
valB = Matrix[byRow][B][usingCellValue].NumericValue if Matrix[byRow][B].Count > usingCellValue else None;

if(descending):
if valB < valA:
Matrix.SwitchColumns(A,B)
else:
if valA < valB:
Matrix.SwitchColumns(A,B)


I am thinking of adding a new parameter which takes a list of column names, and use this to bypass these columns.

Something like:

def SortColumns(fixedcolumns, byRow=0,usingCellValue=0,descending=True):

Answer

While iterating through the columns, You can use the continue statement to skip over columns that you don't want to move. Put these conditions at the start of your two loops:

for A in range(0,Matrix.Count):
    a_name = ??? #somehow get the name of column A
    if a_name in fixedcolumns: continue
    for B in range(0,Matrix.Count):
        b_name = ??? #somehow get the name of column B
        if b_name in fixedcolumns: continue
        if(A==B):
            continue