Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort unique values in of a particular coulmn in pandas?

Tags:

pandas

numpy

I have numerical values in campaign_id column. I want to sort the unique values in a that column but I am not able to do it.

I tried following:

testdata['campaign_id'].unique.sort_values()

OR

testdata['campaign_id'].sort_values.unique()

but above code gives error. How to sort the unique values of particular column.

like image 793
stone rock Avatar asked Sep 18 '25 04:09

stone rock


1 Answers

You need for first numpy.sort, because unique return numpy array:

print (np.sort(testdata['campaign_id'].unique()))

If swap functions use:

print (testdata['campaign_id'].sort_values().unique())

Sample:

testdata = pd.DataFrame({'campaign_id':[7,1,1,4,2,3]})
print (testdata)
   campaign_id
0            7
1            1
2            1
3            4
4            2
5            3
print (np.sort(testdata['campaign_id'].unique()))
[1 2 3 4 7]

print (testdata['campaign_id'].sort_values().unique())
[1 2 3 4 7]
like image 121
jezrael Avatar answered Sep 21 '25 00:09

jezrael