Find the unique values in a column and then sort them

We Are Going To Discuss About Find the unique values in a column and then sort them. So lets Start this Python Article.

Find the unique values in a column and then sort them

How to solve Find the unique values in a column and then sort them

sorted(iterable): Return a new sorted list from the items in iterable.
CODE
import pandas as pd df = pd.DataFrame({'A':[1,1,3,2,6,2,8]}) a = df['A'].unique() print(sorted(a))
OUTPUT
[1, 2, 3, 6, 8]

Find the unique values in a column and then sort them

sorted(iterable): Return a new sorted list from the items in iterable.
CODE
import pandas as pd df = pd.DataFrame({'A':[1,1,3,2,6,2,8]}) a = df['A'].unique() print(sorted(a))
OUTPUT
[1, 2, 3, 6, 8]

Solution 1

sorted(iterable): Return a new sorted list from the items in iterable.

CODE

import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print(sorted(a))

OUTPUT

[1, 2, 3, 6, 8]

Original Author Vineet Kumar Doshi Of This Content

Solution 2

sort sorts inplace so returns nothing:

In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a

Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)

So you have to call print a again after the call to sort.

Eg.:

In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)

[1 2 3 6 8]

Original Author EdChum Of This Content

Solution 3

You can also use the drop_duplicates() instead of unique()

df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a

Original Author Meloun Of This Content

Solution 4

I prefer the oneliner:

print(sorted(df['Column Name'].unique()))

Original Author MDMoore313 Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

ittutorial team

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment