2

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

2
  • stackoverflow.com/a/30575879/4080476 Commented Sep 11, 2015 at 17:41
  • that requires me to make the mapping each time. Which requires me to look at the name. My real data is large and it changes every time. Moreover I need to set as an automatic job that runs everyday. Thanks for the attempt though. Commented Sep 11, 2015 at 17:46

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

Categoricals provide a reasonably easy way to define an arbitrary ordering

In [35]: df['id'] = df['id'].astype('category')

In [39]: df['id'] = (df['id'].cat.reorder_categories(
                         sorted(df['id'].cat.categories, key = lambda x: int(x[1:]), reverse=True)))
In [40]: df.groupby('id').sum()
Out[40]: 
       value
id          
b5789      0
c1112      0
a132       0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.