Shuffle rows by a column in pandas

后端 未结 2 1269
礼貌的吻别
礼貌的吻别 2021-01-21 21:40

I have the following example of dataframe.

    c1     c2
0   1       a
1   2       b
2   3       c
3   4       d
4   5       e

Given a template

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 22:01

    merge

    You can create a dataframe with the column specified in the wanted order then merge.
    One advantage of this approach is that it gracefully handles duplicates in either df.c1 or the list c1. If duplicates not wanted then care must be taken to handle them prior to reordering.

    d1 = pd.DataFrame({'c1': c1})
    
    d1.merge(df)
    
       c1 c2
    0   3  c
    1   2  b
    2   5  e
    3   4  d
    4   1  a
    

    searchsorted

    This is less robust but will work if df.c1 is:

    • already sorted
    • one-to-one mapping

    df.iloc[df.c1.searchsorted(c1)]
    
       c1 c2
    2   3  c
    1   2  b
    4   5  e
    3   4  d
    0   1  a
    

提交回复
热议问题