2

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?

0

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

4

Option 1
Using df.argsort and df.reindex

df

   Review
0     abc
1  foo123
2       b

df = df.reindex((-df.Review.str.len()).argsort()).reset_index(drop=True)
df

  Review
0  foo123
1     abc
2       b

Option 2
Similar solution using np.argsort

df = df.reindex(np.argsort(-df.Review.str.len())).reset_index(drop=True)
df

   Review
0  foo123
1     abc
2       b

Option 3
Using df.sort_values and df.iloc

df = df.iloc[(-df.Review.str.len()).argsort()].reset_index(drop=True)
df

   Review
0  foo123
1     abc
2       b

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.