Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort data in Pandas dataframe alphabetically

I have a dataframe where I need to sort the contents of one column (comma separated) alphabetically:

ID   Data
1     Mo,Ab,ZZz
2     Ab,Ma,Bt
3     Xe,Aa
4     Xe,Re,Fi,Ab

Output:

ID   Data
1     Ab,Mo,ZZz
2     Ab,Bt,Ma
3     Aa,Xe
4     Ab,Fi,Re,Xe

I have tried:

df.sort_values(by='Data')

But this does not work

like image 285
Mazz Avatar asked Mar 19 '20 14:03

Mazz


People also ask

How do you sort data alphabetically in Python?

In Python, sorting a list alphabetically is as easy as passing a list of strings to the sorted() method. Strings are sorted in alphabetical order based on their first letter (A-Z).

How do you put a column in alphabetical order in pandas?

Using reindex() method Finally, if you want to specify column indices in the order you wish them to appear (e.g. in alphabetical order) you can use reindex() method to conform the DataFrame to new index.

How do I sort Panda DataFrame?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.

How do you sort a value count alphabetically?

value_counts() sorted alphabetically. In some cases it is necessary to display your value_counts in an alphabetical order. This can be done easily by adding sort index sort_index(ascending=True) after your value_counts().


1 Answers

You can split, sorting and then join back:

df['Data'] = df['Data'].apply(lambda x: ','.join(sorted(x.split(','))))

Or use list comprehension alternative:

df['Data'] = [','.join(sorted(x.split(','))) for x in df['Data']]

print (df)
   ID         Data
0   1    Ab,Mo,ZZz
1   2     Ab,Bt,Ma
2   3        Aa,Xe
3   4  Ab,Fi,Re,Xe
like image 180
jezrael Avatar answered Oct 23 '22 16:10

jezrael