2

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.

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

6 Comments

Hey, I am getting this error: ValueError: invalid literal for int() with base 10: '345'. The dtype of df['string'] is object
@johndoe - For me working nice, it seems some data related problem, what is print (df.head().to_dict()) ?
Here is the output (It is a bit different from the above df, because it was just sample).
{'string': {0: '-4200.0 -135400.0 -148000.0 -58500.00000000001 -2800.0 -26899.999999999996 -51400.0 -33800.0 -18600.0 -65900.0 -23499.999999999996', 1: '-15200.0 -148000.0 -67700.0 -26000.0 -27300.0 -28599.999999999996 -25799.999999999996 -108199.99999999999 -19900.0 -31900.0 -89400.0 -63300.0', 2: '-31400.0 -12800.0 -1200.0', 3: '-32700.000000000004 -15999.999999999998 -18300.0 -200.0 -7000.0 -99.99999999999999', 4: '0.0 -8100.0 -4399.999999999999'}}
My bad, My original text was in float. I fixed it, and works perfectly. Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.