Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Sorting y value array according to ascending x array

If I had two arrays of the form:

x = [0, 7, 2, 4, 6, 9, 5]

y = [1, 2, 3, 4, 5, 6, 7]

i.e., I have data points at [0,1], [3,2], [x_n,y_n] etc. How would I organise y for a corresonding ascending x value? In other words I end up with ascending values of x:

x = [0, 2, 4, 5, 6, 7, 9]

Matched to their corresponding y values:

y = [1, 3, 4, 7, 5, 2, 6]

I'm guessing I would need to stitch the two arrays together then sort according to x, but I'm not quite sure of the exact syntax for this. Any helps would be greatly appreciated.

like image 803
GCien Avatar asked Aug 14 '15 22:08

GCien


People also ask

How do you sort numbers in an array in ascending order Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

How do you sort an array from ascending to descending in Python?

The sort() method lets you sort a list in ascending or descending order. It takes two keyword-only arguments: key and reverse . reverse determines if the list is sorted in ascending or descending order.


2 Answers

I would use zip with a lambda:

In [55]: x = [0, 7, 2, 4, 6, 9, 5]

In [56]: y = [1, 2, 3, 4, 5, 6, 7]

In [57]: L = sorted(zip(x,y), key=operator.itemgetter(0))

In [58]: new_x, new_y = zip(*L)

In [59]: new_x
Out[59]: (0, 2, 4, 5, 6, 7, 9)

In [60]: new_y
Out[60]: (1, 3, 4, 7, 5, 2, 6)

Don't forget to import operator

like image 164
inspectorG4dget Avatar answered Sep 27 '22 15:09

inspectorG4dget


You can sorted them as tuples after you zip them

>>> sorted((i,j) for i,j in zip(x,y))
[(0, 1), (2, 3), (4, 4), (5, 7), (6, 5), (7, 2), (9, 6)]

To iterate over these pairs, you could do something like

sorted_pairs = sorted((i,j) for i,j in zip(x,y))
for i,j in sorted_pairs:
    # do something with each i and j value, which are x and y respectively

Or you can index directly like

sorted_pairs[0][0]  # x of the first tuple
sorted_pairs[0][1]  # y of the first tuple
sorted_pairs[3][0]  # x of the fourth tuple... etc
like image 25
Cory Kramer Avatar answered Sep 27 '22 17:09

Cory Kramer