Select rows of pandas dataframe from list, in order of list

前端 未结 3 1704
一向
一向 2020-12-17 00:14

The question was originally asked here as a comment but could not get a proper answer as the question was marked as a duplicate.

For a given pandas.Da

3条回答
  •  忘掉有多难
    2020-12-17 00:28

    1] Generic approach for list_of_values.

    In [936]: dff = df[df.A.isin(list_of_values)]
    
    In [937]: dff.reindex(dff.A.map({x: i for i, x in enumerate(list_of_values)}).sort_values().index)
    Out[937]:
       A  B
    2  3  3
    3  4  5
    1  6  2
    

    2] If list_of_values is sorted. You can use

    In [926]: df[df.A.isin(list_of_values)].sort_values(by='A')
    Out[926]:
       A  B
    2  3  3
    3  4  5
    1  6  2
    

提交回复
热议问题