Home > database >  TypeError: unhashable type: 'Series' when attempting to use the replace function
TypeError: unhashable type: 'Series' when attempting to use the replace function

Time:09-14

I am having problems trying to remove substrings from a column that are contained within the string of another column:

df = pd.DataFrame(
    {
        "substring": ["This", "sentence."],
        "id": [1, 1],
        "string": ["This is a sentence.", "This is another sentence."],
    }
)
df["replaced"] = df["string"].str.replace(df["substring"], "")

CodePudding user response:

Use list comprehension:

df["replaced"] = [x.replace(y, "") for x,  y in zip(df["string"], df["substring"])]


print (df)
   substring  id                     string          replaced
0       This   1        This is a sentence.    is a sentence.
1  sentence.   1  This is another sentence.  This is another 
    

CodePudding user response:

Or using apply paradigm

df['replaced'] = df.apply(lambda row:row['string'].replace(row['substring'],''),axis=1)
  • Related