David David - 3 months ago 19
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
s.str.split(',').sort()
. However, I could find no such sort function in Pandas. Any other ideas?

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

Answer

try this:

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