David
David

Reputation: 1256

Pandas sort list returned by 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.

Upvotes: 4

Views: 2836

Answers (2)

Scratch'N'Purr
Scratch'N'Purr

Reputation: 10429

You can use the apply function which is very useful in Pandas.

s.apply(lambda x: ','.join(sorted(x.split(','))))

0    abc,def,ghi
1        abc,ghi

Upvotes: 1

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210882

try this:

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

Upvotes: 3

Related Questions