如何对字母数字大 pandas 索引的降序进行排序. [英] how to sort descending an alphanumeric pandas index.

查看:50
本文介绍了如何对字母数字大 pandas 索引的降序进行排序.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框,看起来像:

I have an pandas data frame that looks like:

df = DataFrame({'id':['a132','a132','b5789','b5789','c1112','c1112'], 'value':[0,0,0,0,0,0,]}) 

df = df.groupby('id').sum()

  value
id          
a132       0
b5789      0
c1112      0

我想对它进行排序,使其看起来像:

I would like to sort it so that it looks like:

       value
id                
b5789      0
c1112      0
a132       0

正在查看数字(尽管是字符串)并按降序排序

which is looking at the number(although string) and sorting as descending

推荐答案

一个简单的解决方案是:

A simple solution is to:

  • 拆分索引以将数字提取到临时键列中
  • 按此列降序排序
  • 删除临时键列
df = DataFrame({'id':['a132','a132','b5789','b5789','c1112','c1112'], 'value':[0,0,0,0,0,0,]}) 

df = df.groupby('id').sum()

df['key'] = df.index
df['key'] = df['key'].str.split('(\d+)').str[1].astype(int)
df = df.sort('key', ascending=False).drop('key', axis=1)

# Result
       value
id          
b5789      0
c1112      0
a132       0

这篇关于如何对字母数字大 pandas 索引的降序进行排序.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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