3

Thank you for your time visiting my post. I have the following dataframe below:

df1
        col1                                    col2
    1   virginia is cold, canada is cold too    virginia is cold, canada is cold too
    2   florida, virginia, washington are good  florida, virginia, washington are good
    3   georgia, alabama, virginia are hot      virginia is cold, canada is cold too
    4   virginia, ohio, new castle are great    hawaii, nebreska is wonderful
    5   hawaii, nebreska is wonderful           virginia, ohio, new castle are great

Also, I have a list containing a string:

lst = ['virginia', 'hot', 'too']

I want to replace the string in the entire dataframe with "xxxxxx" if it matches one of the strings in the list. For instance, my dataframe would look like this after replacement:

 df1
            col1                                    col2
        1   xxxxxx is cold, canada is cold xxxxxx   xxxxxx is cold, canada is cold xxxxxx
        2   florida, xxxxxx, washington are good    florida, xxxxxx, washington are good
        3   georgia, alabama, xxxxxx are xxxxxx     xxxxxx is cold, canada is cold xxxxxx
        4   xxxxxx, ohio, new castle are great      hawaii, nebreska is wonderful
        5   hawaii, nebreska is wonderful           xxxxxx, ohio, new castle are great

So far, I have tried but it does not work:

df1 = df1.replace(lst, "xxxxxx")

3 Answers 3

4

You can create a dictionary from the list of words and use regex:

lst = ['virginia', 'hot', 'too']
df1.replace({w: "xxxxxx" for w in lst}, regex=True)

enter image description here

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

Comments

3
df1.replace(lst, 'x' * 5, regex=True)

                                  col1                                 col2
1  xxxxx is cold, canada is cold xxxxx  xxxxx is cold, canada is cold xxxxx
2  florida, xxxxx, washington are good  florida, xxxxx, washington are good
3    georgia, alabama, xxxxx are xxxxx  xxxxx is cold, canada is cold xxxxx
4    xxxxx, ohio, new castle are great        hawaii, nebreska is wonderful
5        hawaii, nebreska is wonderful    xxxxx, ohio, new castle are great

Comments

2

Try to iterate over list lst like here:

import pandas as pd

...
lst = ['virginia', 'hot', 'too']
for s in lst:
    df1.replace(s, 'xxxxx', inplace=True)

print( df1)

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.