How to replace a exact matching string in Pandas string column

Viewed 52

I have a dataframe like

import pandas as pd

data = {"Column1" : ["Income recorded on books this year not included on Schedule K, lines 1 through 11 (itemize):",
                     "a Tax-exempt interest $ Statement #36",
                     "Statement #36"],
        "Column2" : [254, 258, 356]}

df = pd.DataFrame(data)
print(df)



                                                       Column1                                    Column2
0   Income recorded on books this year not included on Schedule K, lines 1 through 11 (itemize):    254
1   a Tax-exempt interest $ Statement #36                                                           258
2   Statement #36                                                                                   356

I want to replace the string $ Statement #36 in the second row

Tried with the

df['Key'] = df['Column1'].str.replace(r'\b$ Statement #36\b', '')

But I'm not able to replace the string in the column


Desired Output


                                                       Column1                                    Column2
0   Income recorded on books this year not included on Schedule K, lines 1 through 11 (itemize):    254
1   a Tax-exempt interest                                                                           258
2   Statement #36                                                                                   356
2 Answers

You can escape the $ (it's special character in regex) or use regex=False:

data = {
    "Column1": [
        "Income recorded on books this year not included on Schedule K, lines 1 through 11 (itemize):",
        "a Tax-exempt interest $ Statement #36",
        "Statement #36",
    ],
    "Column2": [254, 258, 356],
}

df = pd.DataFrame(data)

df["Column1"] = df["Column1"].str.replace(" $ Statement #36", "", regex=False)
print(df)

Prints:

                                             Column1  Column2
0  Income recorded on books this year not include...      254
1                              a Tax-exempt interest      258
2                                      Statement #36      356

The '$' character in regex is reserved so it needs to be escaped by using \$\.

I also set the regex flag to True.


import pandas as pd

data = {"Column1" : ["Income recorded on books this year not included on Schedule K, lines 1 through 11 (itemize):",
                     "a Tax-exempt interest $ Statement #36",
                     "Statement #36"],
        "Column2" : [254, 258, 356]}

df = pd.DataFrame(data)


df['Key'] = df['Column1'].str.replace(r'\$\ Statement #36', '', regex=True)

print(df['Key'])

output of print(df['Key'])

0    Income recorded on books this year not include...
1                                a Tax-exempt interest
2                                        Statement #36
Related