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?