By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,470 Members | 1,081 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,470 IT Pros & Developers. It's quick & easy.

Replace the last letter when letter matches

P: 15
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:
Expand|Select|Wrap|Line Numbers
  1. data = {'id': ['BP001', ' Ba002', 'CA003', 'EF004', 'Pa005','EP001','EM050','XP095']} 
  2. df = pd.DataFrame(data, columns = ['id'])
  3. df
.

Appreciate your help.
3 Weeks Ago #1

✓ answered by SioSio

If id is always 5 characters.
Expand|Select|Wrap|Line Numbers
  1. df['id'] = df['id'].str.replace(' ','')
  2. df['id'] = df['id'].str[:4] + df['id'].str[-1].replace('5', '0')
  3. df['id'] = df['id'].str[:1] + df['id'].str[1].replace('a', 'Z').replace('A', 'Z') + df['id'].str[2:]
  4.  

Share this Question
Share on Google+
2 Replies


100+
P: 110
If id is always 5 characters.
Expand|Select|Wrap|Line Numbers
  1. df['id'] = df['id'].str.replace(' ','')
  2. df['id'] = df['id'].str[:4] + df['id'].str[-1].replace('5', '0')
  3. df['id'] = df['id'].str[:1] + df['id'].str[1].replace('a', 'Z').replace('A', 'Z') + df['id'].str[2:]
  4.  
2 Weeks Ago #2

P: 15
Hi There,
Thanks for advice.
Kind regards,
Chandan
2 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.