根据特定顺序对熊猫数据框排序

问题描述 投票:1回答:2

给定数据:

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
)
python pandas sorting merge
2个回答
2
投票

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

1
投票

您可能想使用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返回。

© www.soinside.com 2019 - 2024. All rights reserved.