按字符串列的长度对数据框进行排序 [英] Sort dataframe by length of a string column

查看:85
本文介绍了按字符串列的长度对数据框进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python.我有一个包含三列的数据框:

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.

如果我这样做

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

它从'z'开始按字母顺序排序.

It sorts alphabetically, starting with 'z'.

如何获取评论"列中字符串的长度排序?

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

推荐答案

我认为您需要 reset_index :

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

这篇关于按字符串列的长度对数据框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆