簡體   English   中英

使用 pandas 對兩列進行排序並為 dataframe 中的排序值創建新列

[英]Sort Two column and create new columns for sorted values from dataframe using pandas

我有以下 dataframe。 我想對 dataframe d1 中'X'列進行排序,並按照X值保留Y的順序。 然后創建一個名為df2的新 dataframe ,其中排序已完成,但原始 dataframe 應保持原樣。

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

原裝 Dataframe

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

預期 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

這里Y_Sorted根據X值的索引。

Y值將保持與每個x_sorted值相同。

使用DataFrame.sort_valuesDataFrame.add_suffix ,創建默認索引和最后一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM