I would like to write a function which sorts strings in a list by their integer part. These sorted strings will be used later to move some variables in a desired manner in pandas dataframe. This function needs to do everything. In other words it overwrites the given list as a return. Below you can find something I tried:
import re
import pandas
wholeregex = r"^[o][0-9]+" # e.g. "o1", "o9", "o10" etc.
intregexkey = r"^[o]([0-9]+)" # so I'm looking for integer parts only
varslist = list(df.filter(regex=wholeregex).columns) # df was defined somewhere before
# e.g. varslist = ["o3", "o8", "o10", "o1"]
#result should be varslist = ["o1", "o3", "o8", "o10"]
def strintkeysort(regex, m):
lstreturn = []
r = re.compile(regex)
lstreturn = sorted(m, key=int(r.search(m).group(1)))
return lstreturn
varslist = strintkeysort(intregexkey, varslist)
When I run this function I receive this:
Traceback (most recent call last):
File "C:/path/script.py", line 130, in <module>
varslist = strintkeysort(intregexkey, varslist)
File "C:/path/script.py", line 127, in strintkeysort
lstreturn = sorted(m, key=int(r.search(m).group(1)))
TypeError: expected string or bytes-like object
It's based on a @Ashwini Chaudhary's answer (Sort list of strings by a part of the string). What makes me very confused is that when I tried to do this exactly in a way he presented it - everything was fine. So I decided to boost this function and do all at once (with no effect) as an excercise (I'm new in Python).
On the other hand: is there any dedicated solution to do this in pandas?
Thank you in advance.