R.singh
R.singh

Reputation: 269

Move data on top if a value exist in column of a dataframe

I have a DataFrame like

id name isp
z  god  promoted
d  desk anyname
f  zzz  promoted
s  df   nope
ds ddd  det

i want the output dataframe to have the values on top if their isp column value is "promoted" so the output dataframe will look like below:

id name isp
z  god promoted
f  zzz promoted
d  desk anyname
s  df   nope
ds ddd  det

Any help thanks :)

Upvotes: 0

Views: 74

Answers (2)

wwnde
wwnde

Reputation: 26676

Use assign and np.where to createa temporary column sort which you sort with and drop later

import numpy as np
       df=df.assign(sort=np.where(df.isp=='promoted',1,2)).sort_values(by='sort', ascending=True).drop(columns=['sort'])
        print(df)

  id  name       isp
0   z   god  promoted
2   f   zzz  promoted
1   d  desk   anyname
3   s    df      nope
4  ds   ddd       det

Upvotes: 2

BENY
BENY

Reputation: 323306

We can do argsort

df=df.iloc[df.isp.ne('promoted').argsort()]
Out[25]: 
   id  name       isp
0   z   god  promoted
2   f   zzz  promoted
1   d  desk   anyname
3   s    df      nope
4  ds   ddd       det

Upvotes: 1

Related Questions