4

I want to know to sort each list of a data frame column(pandas). For example:

id       values
------------------------
 1      ['cdf','abc','efg']
 2      ['xyz' ,'rsy','abc']

Expected :

 id       values
------------------------
 1      ['abc','cdf','efg']
 2      ['abc' ,'rsy','xyz']

Thanks: I would also like to know the same if comma seperated strings are present instead of list.

1 Answer 1

9

Simply using apply with sorted

df['values'].apply(sorted)

0    [abc, cdf, efg]
1    [abc, rsy, xyz]
Name: values, dtype: object

For comma separated values, thanks @AChampion:

df = pd.DataFrame({'id': [1,2], 'values': ['cdf, abc, efg', 'xyz, rsy, abc']})
df['values'].apply(lambda x: ','.join(sorted(x.split(','))))

0     abc, efg,cdf
1     abc, rsy,xyz
Name: values, dtype: object

You can also use a list comprehension to increase performance:

df['values'] = [','.join(sorted(i.split(','))) for i in df['values']]
Sign up to request clarification or add additional context in comments.

1 Comment

And df['values'].apply(lambda x: ','.join(sorted(x.split(',')))) for comma separated strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.