Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the lists in dataframe column

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.

like image 989
Poornesh V Avatar asked Oct 17 '25 15:10

Poornesh V


1 Answers

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']]
like image 68
user3483203 Avatar answered Oct 19 '25 05:10

user3483203



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!