Firenze
Firenze

Reputation: 367

Is there a way to sort a pandas dataframe by column of numerical strings?

Suppose my dataframe df is as below

value_id = ['1_1', '1_2', '1_5', '10_1', '2_2', '3_2']
value_age = [28, 34, 54, 24, 12, 56]
df = pd.DataFrame({'id':value_id, 'age':value_age})

I want to sort this dataframe according to the first column (i.e. id). I want an output like this

id     age
1_1    28
1_2    34
1_5    54
2_2    12
3_2    56
10_1   24

Upvotes: 1

Views: 102

Answers (1)

Ch3steR
Ch3steR

Reputation: 20669

You can set id as index and use df.reindex, and use sorted with custom key parameter.

def f(x):
    v, v1 = map(int, x.split('_'))
    return v, v1

df.set_index('id').reindex(sorted(df.id,key=f))

      age
id
1_1    28
1_2    34
1_5    54
2_2    12
3_2    56
10_1   24

Upvotes: 4

Related Questions