I have a dataframe which looks like this
JavaScript
x
11
11
1
pd.DataFrame({'A': [5, 2, 0, 0, -3, -2, 1]}).sort_values('A')
2
Out[6]:
3
A
4
4 -3
5
5 -2
6
2 0
7
3 0
8
6 1
9
1 2
10
0 5
11
I would like to have “0” values at the end when sorting so my resulting dataframe looks like this.
JavaScript
1
9
1
A
2
4 -3
3
5 -2
4
6 1
5
1 2
6
0 5
7
2 0
8
3 0
9
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:
JavaScript
1
2
1
df.iloc[df['A'].replace(0, np.nan).to_numpy().argsort()]
2
JavaScript
1
9
1
A
2
4 -3
3
5 -2
4
6 1
5
1 2
6
0 5
7
2 0
8
3 0
9