To sort the Numpy array by x array

Asked 2 years ago, Updated 2 years ago, 54 views

Number Pi array is

x=[x3,x6,x1,x4,x2,x5,x5] Here x1<x2<x3<x4<x5<x6

y=[y3,y6,y1,y4,y2,y5,y5] Don't know that the value of y is large or small

If you change x to ascending order using the np.sort() function, x=[x1,x2,x3,x4,x5,x6] This is how it changes. At this time, I want to change the y-array of the same location as the x-value changed, what should I do?

For example, x1 is initially in the x[2]th array and y1 is also located in y[2]. If you change only x in ascending order, x1 comes to the position of x[0], where y1 also comes to y[0] Is there a way?

y must not be in the same ascending order as x.

I think you are using indexing, so I would appreciate it if you could help me.

python numpy

2022-09-20 10:18

2 Answers

>>> x = [ 2, 3, 1, 4, 5 ]
>>> y = [ 22, 33, 11, 44, 55 ]
>>> xy = list(zip(x, y))
>>> xy
[(2, 22), (3, 33), (1, 11), (4, 44), (5, 55)]
>>> sorted(xy)
[(1, 11), (2, 22), (3, 33), (4, 44), (5, 55)]
>>> list(zip(*sorted(xy)))[1]
(11, 22, 33, 44, 55)
>>> import numpy as np
>>> x
[2, 3, 1, 4, 5]
>>> y
[22, 33, 11, 44, 55]
>>> x = np.array(x)
>>> y = np.array(y)
>>> np.argsort(x)
array([2, 0, 1, 3, 4], dtype=int64)
>>> y_ = y[np.argsort(x)]
>>> y_
array([11, 22, 33, 44, 55])


2022-09-20 10:18

How about this?


x=[4, 1, 3, 2, 5, 7]
y=[1, 2, 3, 4, 5, 6]
new_y = []
d = sorted(dict(zip(x, y)).items())
for i in d:
    new_y.append(i[1])

print(new_y)


2022-09-20 10:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.