## dplyr R在pandas 中安排相同的功能

R代码：

df = data.frame(A = c("apple","cherry","orange","banana"), B = c(25,37,15,28))
df

``   A  B``

1 apple 25
2 cherry 37
3 orange 15
4 banana 28

my_order = c(2,3,4,1)
dplyr::arrange(df,my_order)

``   A  B``

1 banana 28
2 apple 25
3 cherry 37
4 orange 15

Python代码：

import pandas as pd

df = pd.DataFrame({'A': ["apple","cherry","orange","banana"], 'B': [25,37,15,28]})
print(df)

``    A   B``

0 apple 25
1 cherry 37
2 orange 15
3 banana 28

my_order = [1,2,3,0]
df.iloc[my_order]

``    A   B``

1 cherry 37
2 orange 15
3 banana 28
0 apple 25

Python

• 一码平川MACHEL
2019-07-17 23:26:40

你正在传递argsorted索引arrange。你可以做同样的事情iloc，但你必须得到argsort你的指数得到它的逆。

my_order = [2,3,4,1]
df.iloc[pd.np.argsort(my_order)]

``    A   B``

3 banana 28
0 apple 25
1 cherry 37
2 orange 15

检查

df.loc[pd.Series(my_order,index=df.index).sort_values().index]
Out[42]:

``    A   B``

3 banana 28
0 apple 25
1 cherry 37
2 orange 15

解决方法：

import pandas as pd

df = pd.DataFrame({'A': ["apple","cherry","orange","banana"], 'B': [25,37,15,28]})

print(df)

df['index']=[2,3,4,1]
df.set_index('index',inplace=True)
df.sort_index(inplace=True)

print(df)

0 0
+ 订阅