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':[1,3,5,6], 'Y':[0.5,0.7,0.2,0.9]}
df= pd.DataFrame(d1)
Original Dataframe
X Y
0 1 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.
Use DataFrame.sort_values
, DataFrame.add_suffix
, create default index and last concat
:
df1 = (df[['X','Y']].sort_values('X', ascending=False)
.add_suffix('_sorted')
.reset_index(drop=True))
df = pd.concat([df, df1], axis=1)
print (df)
X Y X_sorted Y_sorted
0 1 0.5 6 0.9
1 3 0.7 5 0.2
2 5 0.2 3 0.7
3 6 0.9 1 0.5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.