Boosted_d16 Boosted_d16 - 1 year ago 84
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
:param usingCellValue: When there are multiple values within a cell use this
to control which value row within each cell is used for sorting
:param descending: Determines the order in which the values should be

for A in range(0,Matrix.Count):
for B in range(0,Matrix.Count):
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 valB < valA:
if valA < valB:

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download