Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dataframe by length of a string column [duplicate]

Using Python. I have a dataframe with three columns:

Author | Title | Reviews

I want to sort by the length of the string in the Reviews column.

If I do

df.sort_values('Review', ascending = False)

It sorts alphabetically, starting with 'z'.

How do I get it to sort by the length of the string in the Reviews column?

like image 854
Slothrop Avatar asked Dec 31 '25 15:12

Slothrop


1 Answers

I think you need len for lengths assign to index, sort_index and last reset_index:

df = pd.DataFrame({'Author':list('abcdef'),
                   'Title ':list('abcdef'),
                   'Review':['aa', 'aasdd', 'dwd','dswee dass', 'a', 'sds']})

print (df)
  Author      Review Title 
0      a          aa      a
1      b       aasdd      b
2      c         dwd      c
3      d  dswee dass      d
4      e           a      e
5      f         sds      f

df.index = df['Review'].str.len()
df = df.sort_index(ascending=False).reset_index(drop=True)
print (df)
  Author      Review Title 
0      d  dswee dass      d
1      b       aasdd      b
2      c         dwd      c
3      f         sds      f
4      a          aa      a
5      e           a      e
like image 62
jezrael Avatar answered Jan 03 '26 05:01

jezrael



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!