给定数据:
df = pd.DataFrame(dict(
a = ['cup', 'plate', 'apple', 'seal'],
b = ['s','sf', 'wer', 'sdfg']
))
哪个是:
a b
0 cup s
1 plate sf
2 apple wer
3 seal sdfg
如何订购
apple
seal
cup
plate
一种有效但似乎过大的方法:
ordering = pd.DataFrame(dict(
a = [ "apple", "seal", "cup", "plate" ],
c = [0,1,2,3]
))
pd.merge(df, ordering, left_on="a", right_on="a", how="left").sort_values(["c"]).drop(
["c"], axis=1
)
IIUC Categorical
df=df.iloc[pd.Categorical(df.a, ['apple','seal','cup','plate']).argsort()]
df
Out[235]:
a b
2 apple wer
3 seal sdfg
0 cup s
1 plate sf
您可能想使用a
作为索引,然后使用.loc索引技巧:
order = ["apple", "seal", "cup", "plate"]
df.set_index('a').loc[order].reset_index()
给出
a b
0 apple wer
1 seal sdfg
2 cup s
3 plate sf
关于后续问题,如果在原始数据帧的末尾添加一个苹果,则会返回多个苹果:
b
a
apple wer
apple sasda
seal sdfg
cup s
plate sf
索引不必唯一。如果索引中包含duplicates,则所有这些都将由.loc
返回。