how to sort descending an alphanumeric pandas index.

后端 未结 2 764
长发绾君心
长发绾君心 2021-01-15 02:01

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,]}) 
         


        
2条回答
  •  -上瘾入骨i
    2021-01-15 02:54

    A simple solution is to:

    • split the index to extract the number in a temporary key column
    • sort by this column descending
    • drop the temporary key column

    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
    

提交回复
热议问题