按字符串列的长度对数据框进行排序

编程入门 行业动态 更新时间:2024-10-26 02:28:25
本文介绍了按字符串列的长度对数据框进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用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?

推荐答案

我认为您需要 len 表示分配给索引的长度, sort_index 和最后一个 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

更多推荐

按字符串列的长度对数据框进行排序

本文发布于:2023-10-18 03:22:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502928.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:串列   长度   字符   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!