john doe
john doe

Reputation: 435

How can I sort numbers in a string in pandas?

I have a dataframe like this:

id   String
1    345 -456 -13  879
2    158 -926 -81  249 35 -4 -53  9
3    945 -506 -103

I want to sort it in desending order like this

id   String
1    879 345 -13 -457
2    249 158 35 9 -4 -53 -81 -926
3    945 -103 -506

I tried this:

df['string'] = df['string'].str.split(' ').map(lambda x: ' '.join(sorted(x)))

The above function do some kind of sorting but not the way I want it.

Upvotes: 2

Views: 393

Answers (1)

jezrael
jezrael

Reputation: 863741

First is necessary convert values to integers, sorting and then convert to strings back:

f = lambda x: ' '.join(map(str, sorted(map(int, x), reverse=True)))
#another solution
#f = lambda x: ' '.join(str(z) for z in sorted((int(y) for y in x), reverse=True))
df['string'] = df['string'].str.split().map(f)
print (df)
   id                        string
0   1              879 345 -13 -456
1   2  249 158 35 9 -4 -53 -81 -926
2   3                 945 -103 -506

Or:

f = lambda x: ' '.join(map(str, sorted(map(int, x.split()), reverse=True)))
df['string'] = df['string'].map(f)

Upvotes: 4

Related Questions