Reputation: 1256
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
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
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