1

I'm trying to replace specific characters in a data frame just if the string of the column starts with the characters specified. I mean, the df is as below:

UBICACION NAME
AL03 Joe
FL03 Maria
AL07 Karla
DAL5 Marco

The desired output would be:

UBICACION NAME
FL03 Joe
FL03 Maria
FL07 Karla
DAL5 Marco

This is my try:

df['UBICACION'] = df['UBICACION'].replace ("FL","AL")

The last sentence is not working, cause' it changes all the word, it just keeps the specified characters

Hope you can help me, I'm a little bit new on this. Best regards.

3
  • When do you want to change the FL to AL? Commented Aug 5, 2021 at 1:20
  • Every Time that the string starts with "FL" :) Commented Aug 5, 2021 at 1:22
  • 1
    I edited the title of the question to reflect the question you appear to be actually asking. Please feel free to re-correct it if I got it wrong. Commented Aug 5, 2021 at 1:29

2 Answers 2

5

DataFrame.replace includes a regex=True option, so you can use ^AL:

df['UBICACION'] = df['UBICACION'].replace('^AL', 'FL', regex=True)


#   UBICACION   NAME
# 0 FL03        Joe
# 1 FL03        Maria
# 2 FL07        Karla
# 3 DAL5        Marco
Sign up to request clarification or add additional context in comments.

3 Comments

WOW it really worked, just a quick question, why does '^' is used for?
when ^ is at the beginning of a regex, it's a special regex character that means "beginning of the line"
here's a decent summary of other special characters in regular expressions
0

try this:

df["UBICACION"] = df["UBICACION"].apply(lambda x: f"FL{x[2:]}" if x.startswith("AL") else x)

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.