I have a pandas dataframe, say:
df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])
or:
col 1 col2 col 3
0 a 3 3
1 b 2 5
2 c 4 9
3 d 1 43
If I want to sort by col2, I can use df.sort, and that will sort ascending and descending.
However, if I want to sort the rows so that col2 is: [4, 2, 1, 3], how would I do that?
Try this:
sortMap = {4:1, 2:2, 1:3,3:4 }
df["new"] = df2['col2'].map(sortMap)
df.sort_values('new', inplace=True)
df
col1 col2 col3 new
2 c 4 9 1
1 b 2 5 2
3 d 1 43 3
0 a 3 3 4
alt method to create dict:
ll = [4, 2, 1, 3]
sortMap = dict(zip(ll,range(len(ll))))
One way is to convert that column to a Categorical
type, which can have an arbitrary ordering.
In [51]: df['col2'] = df['col2'].astype('category', categories=[4, 1, 2, 3], ordered=True)
In [52]: df.sort_values('col2')
Out[52]:
col 1 col2 col 3
2 c 4 9
3 d 1 43
1 b 2 5
0 a 3 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With