IamWarmduscher
IamWarmduscher

Reputation: 965

How do I move a particular row up in a Pandas dataframe?

Given the following dataframe:

df_test = pd.DataFrame(
    [['18-24', 334725], ['25-44', 698261], ['45-64', 273087], ['65+', 15035],['<18', 80841]],
    columns=['age_group', 'total_arrests']
)

enter image description here

How would I move the last row (index=4) to the top of the dataframe? I need to do this because when I plot this in matplotlib, the <18 group appears at the end, not the beginning:

enter image description here

Upvotes: 1

Views: 189

Answers (1)

jezrael
jezrael

Reputation: 863751

Use Series.argsort with compare column for not equal for indices and pass to DataFrame.iloc:

df_test = df_test.iloc[df_test['age_group'].ne('<18').argsort()]
print (df_test)
  age_group  total_arrests
4       <18          80841
0     18-24         334725
1     25-44         698261
2     45-64         273087
3       65+          15035

If value is always last and index values are unique change order with indexing by DataFrame.loc:

df_test = df_test.loc[df_test.index[-1:].tolist() + df_test.index[:-1].tolist()]
print (df_test)
  age_group  total_arrests
4       <18          80841
0     18-24         334725
1     25-44         698261
2     45-64         273087
3       65+          15035

Upvotes: 1

Related Questions