Plain python, with sorted
and key
You could define a function in order to split the index into a pair of letters (as string) and numbers (as integer):
d1 = ['c1','ac2','c3','c4','c5','c6','c7','c8','c9','c10','c11','a']
import re
pattern = re.compile('([a-z]+)(\d*)', re.I)
def split_index(idx):
m = pattern.match(idx)
if m:
letters = m.group(1)
numbers = m.group(2)
if numbers:
return (letters, int(numbers))
else:
return (letters, 0)
As an example:
>>> split_index('a')
('a', 0)
>>> split_index('c11')
('c', 11)
>>> split_index('c1')
('c', 1)
You can then use this function as a key to sort the indices lexicographically:
print(sorted(d1, key=split_index))
# ['a', 'ac2', 'c1', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10', 'c11']
Pandas sort
You could create a new, temporary column with the tuples from split_index
, sort according to this column and delete it:
import pandas as pd
df = pd.DataFrame(
{"i1":[1,1,1,1,2,4,4,2,3,3,3,3],
"i2":[1,3,2,2,1,1,2,2,1,1,3,2],
"d1":['c1','ac2','c3','c4','c5','c6','c7','c8','c9','c10','c11','a']}
)
df['order'] = df['d1'].map(split_index)
df.sort_values('order', inplace=True)
df.drop('order', axis=1, inplace=True)
df.set_index('d1', inplace=True)
print(df)
It outputs:
i1 i2
d1
a 3 2
ac2 1 3
c1 1 1
c3 1 2
c4 1 2
c5 2 1
c6 4 1
c7 4 2
c8 2 2
c9 3 1
c10 3 1
c11 3 3