David David - 1 year ago 82
Python Question

Pandas sort list of str.split()

Given a Pandas Series of type str, I want to sort the result returned by str.split.

For example, given the Series

s = pd.Series(['abc,def,ghi','ghi,abc'])

I would like to get

s2 = pd.Series(['abc,def,ghi','abc,ghi'])

as a result.

How can I do this? I thought about something like
. However, I could find no such sort function in Pandas. Any other ideas?

Another idea would be to use the function
, then rearange the columns and finally do something like
. However, I could not find such a function

Answer Source

try this:

In [70]: s.str.split(',').map(lambda x: ','.join(sorted(x)))
0    abc,def,ghi
1        abc,ghi
dtype: object