0

I have a column in a dataframe with has free text. I want to replace words starting with AA and ending with AA in the text. Can anyone suggest how to do this?

3
  • use df['column].apply(lambda x: tada)' Commented Feb 19, 2021 at 15:59
  • How do I write pattern to start with AA and end with AA Commented Feb 19, 2021 at 16:02
  • strings have both a startswith and endswith method. You could also use regular expressions. For this they are perhaps overkill, but in python you will likely need to learn how to use them sooner or later. Commented Feb 19, 2021 at 16:07

2 Answers 2

1

Here's a simple solution using replace str method and regex pattern

>>> df=pandas.DataFrame({'example':['AAhelloAA','Arreviour','Dunno this is a example of it','a knee','an arrow','AAnother example ofAA']})
>>> print(df)
                        example
0                      AAhelloAA
1                      Arreviour
2  Dunno this is a example of it
3                         a knee
4                       an arrow
5          AAnother example ofAA
>>> df['example'].str.replace(r'(AA).*?(AA)','NEW CHANGE!')  
0                      NEW CHANGE!
1                        Arreviour
2    Dunno this is a example of it
3                           a knee
4                         an arrow
5                      NEW CHANGE!
Name: example, dtype: object

Gotta clarified that the pattern in regex it works in any text that starts and ends with AA.

Sign up to request clarification or add additional context in comments.

Comments

0

Use Regex to capture the group and do with it as you please. To return just the text surrounded by AA on each side, do this:

df.column.replace(r"AA(.*)AA", r"\1", regex=True)

\1 is the regex group representing the text portion surrounded by the AA's.

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.