'Sort Two column and create new columns for sorted values from dataframe using pandas

I have below dataframe. I want to sort column 'X' from dataframe d1 and keep the order Y as per X values. and then create a new dataframe called df2 where sorting is done but original dataframe should remain as it is.

import pandas as pd
d1 = {'X':[4,3,5,6], 'Y':[0.5,0.7,0.2,0.9]}
df= pd.DataFrame(d1)

Original Dataframe

   X    Y
0  4  0.5
1  3  0.7
2  5  0.2
3  6  0.9

Expected DataFrame

   X    Y  X_Sorted  Y_Sorted
0  4  0.5         6       0.9
1  3  0.7         5       0.2
2  5  0.2         4       0.5
3  6  0.9         3       0.7

Here Y_Sorted as per index of X values.

Y values will remain same as per x_sorted values.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source