BrooklynSon
BrooklynSon

Reputation: 2103

Numpy Sort Class Which Uses Dictionary Attributes

class Evaluations():
    columns = {0: "participationKey", 1: "focusKey"}
    participationKey = {"high": 3, "med": 2, "low": 1}
    focusKey = {"high": 3, "med": 2, "low": 1}

    def __init__(self):
        self.data = []

    def addData(self, participation, focus):
        self.data.append((participation focus))

If I bind the above class w/another function for example:

def bindClass()
    eval = Evaluations()
    eval.addData('high','high')
    eval.addData('low', 'low')
    eval.addData('med','med')

How would I sort the data using NumPy, then iterate to show results in print? Thanks!

Upvotes: 2

Views: 1912

Answers (1)

hunse
hunse

Reputation: 3255

Since you're storing your data in a list, I'm guessing it's not too huge, so Python's builtin sorted routine should do just fine; you probably don't need Numpy. I'm also assuming that you want to map the values stored in data using participationKey and/or focusKey for sorting. You could do something like

data = sorted(data, key=lambda pf: participationKey[pf[0]])

to sort by the mapped participation key. Or if you want to sort by the sum of the participation key and focus key

data = sorted(data, key=lambda pf: participationKey[pf[0]] + focusKey[pf[1]])

In these examples, you're passing the sorted function a "key", which is a callable function that maps list elements (in your case participation-focus pairs, which I've called pf) to numeric values that Python will sort in the way you want.

To iterate and print, just use a for loop

for pf in data:
    print "participation = %s, focus = %s" % pf

If you have to use Numpy, then you'll need to create a Numpy array of indices for sorting, then use argsort to get indices that will sort the data, then apply this back to data.

import numpy as np
inds = np.array([participationKey[pf[0]] for pf in data])
sort_inds = np.argsort(inds)
sorted_data = [data[ind] for ind in sort_inds]

Upvotes: 3

Related Questions