Pandas的DataFrame某一列是字符串类型,如何按照字符串的长度对该DataFrame排序

数据如下:

df = pd.DataFrame({
    'name': ['六个六撒', '张三', '李四全', '王'],
    'age': ['6', '3', '2', '5']
})

在这里插入图片描述

按照name列中元素的长度由小到大排序:

df = pd.DataFrame({
    'name': ['六个六撒', '张三', '李四全', '王'],
    'age': ['6', '3', '2', '5']
})
my_index = df.name.str.len().sort_values().index
df.reindex(my_index)

排序后的结果:
在这里插入图片描述

发布了138 篇原创文章 · 获赞 224 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43546676/article/details/103642680
今日推荐