Replace the last letter when letter matches

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ck25python
    New Member
    • Jan 2020
    • 20

    Replace the last letter when letter matches

    Hi There,

    If the last letter contains number 5 then I want to replace it with 0.

    id PA005 and XP095 contain 5 at the last I want to replace 5 to 0.
    In a similar fashion, if the second letter contains A then replace it with Z. ID Ba002, CA003 and Pa005 contains the second letter A and i want to replace it to Z

    Below is the dataframe:
    Code:
    data = {'id': ['BP001', ' Ba002', 'CA003', 'EF004', 'Pa005','EP001','EM050','XP095']} 
    df = pd.DataFrame(data, columns = ['id'])
    df
    .

    Appreciate your help.
  • SioSio
    Contributor
    • Dec 2019
    • 272

    #2
    If id is always 5 characters.
    Code:
    df['id'] = df['id'].str.replace(' ','')
    df['id'] = df['id'].str[:4] + df['id'].str[-1].replace('5', '0')
    df['id'] = df['id'].str[:1] + df['id'].str[1].replace('a', 'Z').replace('A', 'Z') + df['id'].str[2:]

    Comment

    • ck25python
      New Member
      • Jan 2020
      • 20

      #3
      Hi There,
      Thanks for advice.
      Kind regards,
      Chandan

      Comment

      Working...