2

I can sort dataframe by column like this:

df.sort(columns='sort_index', inplace=True)

And I can sort array with ignoring prefixes like this:

array.sort(key=lambda element: re.sub(re, "", element))

But how to sort dataframe with ignoring prefixes?

2
  • 1
    Can you add data sample? Commented Feb 21, 2018 at 13:46
  • Add a "key" column to your dataframe with the re.sub logic then sort on that "key". After sort, drop('key', axis=1). Plus you'll need to use sort_values. Commented Feb 21, 2018 at 13:47

1 Answer 1

2

I think you need str.replace with argsort for indices and then select by iloc what reorder rows:

df = pd.DataFrame({
    'B': list(range(9)), 
}, index=['1s','2d','2a','1c','22d','1b','2b','1c','4d'])
print (df)
     B
1s   0
2d   1
2a   2
1c   3
22d  4
1b   5
2b   6
1c   7
4d   8

idx = df.index.str.replace('\D+', '').astype(int).argsort()
df = df.iloc[idx]
print (df)
     B
1s   0
1c   3
1b   5
1c   7
2d   1
2a   2
2b   6
4d   8
22d  4
Sign up to request clarification or add additional context in comments.

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.