Replace "\\" from string with space using Python

Viewed 73

The dataframe consists of df["Notes"] column that contains text for each of the observation.The following is the snippet for couple of observations:

   'Storm Data (Vol. 11, No. 8) reports associated with Hurricane Camille (August 1969) indicate \\... substantiated amounts up to 31 inches ... falling mainly in Nelson and adjacent counties ....\\" The 14.28 inches at Williamsburg fell in conjunction with Hurricane Floyd."',

   'These were values of 89.90\\ at Montebello Fish Hatchery and 87.33\\" at Roanoke 5.8 SW (CoCoRaHS). These were determined not to be valid statewide precipitation records. A separate report detailing these values is available here."',

I was trying to replace "\" from text with space("") using the below code:

df["Notes"] = df["Notes"].replace('\\',"")

The code is not giving any error but I am unable to replace "\" with "".The data type of the column is "O".

1 Answers

If you want to apply a string function to a pandas series, you need to apply .str to the column and then .replace.

df["Notes"] = df["Notes"].str.replace('\\',"")

Essentially, the .str method allows pandas to iterate over the string objects in the column and run str.replace('\\',"") on each element.

Related