1
name qty id
orange4 1 10pqw102
orange3 2 10pxa920
apple2 3 20asa399
apple1 4 20asw987

Expected output

name qty id
orange4 1 10pqw102
apple2 3 20asa399
orange3 2 10pxa920
apple1 4 20asw987
1
  • can you add some detail to your post, as well as your own effort and expected output?
    – Umar.H
    Feb 15, 2021 at 11:34

1 Answer 1

1

Use key parameter in DataFrame.sort_values:

df = df.sort_values(by='id', key=lambda col: col.str[-3:].astype(int))

For oldier pandas versions:

df = df.iloc[df['id'].str[-3:].astype(int).argsort()]
2
  • or df.sort_values(df['ColC'].str.extract('(\d{3}$)').astype(int)) but i think OP wants to be sorted by ID column not ColC
    – Umar.H
    Feb 15, 2021 at 11:41
  • 1
    @Manakin - thank you, it was first OP data.
    – jezrael
    Feb 15, 2021 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.