Allie H Allie H - 1 month ago 6
Python Question

python - sorting floats within elements of an array based on another array

I have a data array looks, for example, like:

data = [
[1.4, 2.6, 7.3, 4.2],
[1.1, 2.0, 6.4, 1.0],
[5.1, 6.2, 5.3, 9.9]
]


and another array with class labels:

class_labels = ['a', 'b', 'a', 'b']


Each of the class labels corresponds to certain floats in each element of the data array (e.g., class
'a'
corresponds to
1.4
and
7.3
from
data[0]
,
1.1
and
6.4
from
data[1]
, and
5.1
and
5.3
from
data[0]
).

I understand from other posts how I could go about sorting one array based on another array, but is it possible to sort the
class_labels
array alphabetically, also sorting the corresponding floats within each element of the data array?

It's possible I've totally gone about this wrong - if I want to be able to later access certain floats from each element (i.e., only floats corresponding to a given class label), will that be possible?

Thanks for any advice!

Answer

It is possible to sort arrays based on the sort order of another, but I would suggest a dictionary instead as it'll probably be easier to work with. Something like:

data_by_class = {label:[] for label in set(class_labels)}
for row in data:
    for idx in range(len(row)):
        data_by_class[class_labels[idx]].append(row[idx])

which would result in

{ 'a':[1.4, 7.3, 1.1, 6.4, 5.1, 5.3], 'b': [2.6, 4.2, 2.0, 1.0, 6.2, 9.9] }