One could try something like this, by performing a sort on a numbered version of the index
import pandas as pd
# Create a DataFrame example
df = pd.DataFrame(
{'Year': [1991 ,2004 ,2001 ,2009 ,1997],
'Age': [27 ,25 ,22 ,34 ,31],
},
index = ['Com_Lag_1' ,'Com_Lag_12' ,'Com_Lag_3' ,'Com_Lag_24' ,'Com_Lag_5'])
# Add of a column containing a numbered version of the index
df['indexNumber'] = [int(i.split('_')[-1]) for i in df.index]
# Perform sort of the rows
df.sort(['indexNumber'], ascending = [True], inplace = True)
# Deletion of the added column
df.drop('indexNumber', 1, inplace = True)
Edit 2017 - V1:
To avoid SettingWithCopyWarning:
df = df.assign(indexNumber=[int(i.split('_')[-1]) for i in df.index])
Edit 2017 - V2 for Pandas Version 0.21.0
import pandas as pd
print(pd.__version__)
# Create a DataFrame example
df = pd.DataFrame(
{'Year': [1991 ,2004 ,2001 ,2009 ,1997],
'Age': [27 ,25 ,22 ,34 ,31],
},
index = ['Com_Lag_1' ,'Com_Lag_12' ,'Com_Lag_3' ,'Com_Lag_24' ,'Com_Lag_5'])
df.reindex(index=df.index.to_series().str.rsplit('_').str[-1].astype(int).sort_values().index)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…