2

CONTEXT

Let's say I have df, which consists of a column of delimited strings that I would like to sort.

import pandas as pd

df = pd.DataFrame({'sort_me':['foo; bar','foo; bar','bar; foo']})

df

     sort_me
0   foo; bar
1   foo; bar
2   bar; foo

DESIRED OUTPUT

Given I would like to sort these strings, this would be my desired output:

     sort_me
0   bar; foo
1   bar; foo
2   bar; foo

WHAT I HAVE TRIED

I figured I could turn each delimited string into a list with str.split(), sort that list, and then join that list back together with join() using a lambda function:

df.sort_me.str.split(';').apply(sorted).apply(lambda x: ';'.join(x))

    sort_me
0   bar;foo
1   bar;foo
2   foo;bar

I thought I was so clever for this solution, but it appears to "unsort" any column that was already coincidentally sorted (see: index 2). Why is sorted displaying such behavior? Is there a better way to go about this problem?

2
  • 2
    you have leading spaces in your second column after splitting. that is why your sort works as it works. strip it or split on "; ". Commented Sep 18 at 21:02
  • Of course, you could do this far more efficiently by sorting within the dictionary and then constructing the DataFrame. In my tests I see a performance improvement of ~135% doing it this way Commented Sep 19 at 7:26

1 Answer 1

2

Each list from split() needs to be sorted too. Also, the separator in the sample contains an space that needs to be considered

import pandas as pd

df = pd.DataFrame({'sort_me':['foo; bar','foo; bar','bar; foo']})

df['sort_me'] = df.sort_me.str.split('; ').apply(lambda x: sorted(x)).apply(lambda x: '; '.join(x))

# probably needed
# df.sort_values(by="sort_me",inplace=True)

print(df)
    sort_me
0  bar; foo
1  bar; foo
2  bar; foo
Sign up to request clarification or add additional context in comments.

1 Comment

No need for the extra lambda: you can replace .apply(lambda x: sorted(x)) with .apply(sorted)

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.