I have a datafrmae lke this
df_crossplot
the index is 1A22, 10A22,11A22,2A22,21A22
value
1A22 10
10A22 12
11A22 11
2A22 15
12A22 21
3A22 25
What I like to do is sort index based on the number before A, like this
value
1A22 10
2A22 15
3A22 25
10A22 12
11A22 11
12A22 21
The one I do is this with an error
df_crossplot=df_crossplot.sort_index(key=lambda x: float(x.str.split('A')[0]))
TypeError: float() argument must be a string or a number, not 'list'
seem like x inside lambda function is a list instead of each individual component of a series,
How to do it? Thanks
CodePudding user response:
use pandas func in key
df.sort_index(key=lambda x: x.str.split('A').str[0].astype('int'))
CodePudding user response:
Why not create a new column and sort by it?:
df['sort_col'] = df.index.str.split('A')[0].astype(int)
CodePudding user response:
natsort
would do work easily if you want to sort index
from natsort import natsorted
print(df.reindex(index=natsorted(df.index)))