Skip to content
Advertisement

Pandas sort column values with “0” values at end of column

I have a dataframe which looks like this

pd.DataFrame({'A': [5, 2, 0, 0, -3, -2, 1]}).sort_values('A')
Out[6]: 
   A
4 -3
5 -2
2  0
3  0
6  1
1  2
0  5

I would like to have “0” values at the end when sorting so my resulting dataframe looks like this.

   A
4 -3
5 -2
6  1
1  2
0  5
2  0
3  0

Is there a simple (1 line of code) solution?

Advertisement

Answer

First mask the zeros then use argsort on column A to get the indices that would sort the dataframe:

df.iloc[df['A'].replace(0, np.nan).to_numpy().argsort()]

   A
4 -3
5 -2
6  1
1  2
0  5
2  0
3  0
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement