Replace all occurrences of a string in a pandas dataframe (Python) Replace all occurrences of a string in a pandas dataframe (Python) pandas pandas

Replace all occurrences of a string in a pandas dataframe (Python)


You can use replace and pass the strings to find/replace as dictionary keys/items:

df.replace({'\n': '<br>'}, regex=True)

For example:

>>> df = pd.DataFrame({'a': ['1\n', '2\n', '3'], 'b': ['4\n', '5', '6\n']})>>> df   a    b0  1\n  4\n1  2\n  52  3    6\n>>> df.replace({'\n': '<br>'}, regex=True)   a      b0  1<br>  4<br>1  2<br>  52  3      6<br>


It seems Pandas has change its API to avoid ambiguity when handling regex. Now you should use:

df.replace({'\n': '<br>'}, regex=True)

For example:

>>> df = pd.DataFrame({'a': ['1\n', '2\n', '3'], 'b': ['4\n', '5', '6\n']})>>> df   a    b0  1\n  4\n1  2\n  52  3    6\n>>> df.replace({'\n': '<br>'}, regex=True)   a      b0  1<br>  4<br>1  2<br>  52  3      6<br>


You can iterate over all columns and use the method str.replace:

for col in df.columns:   df[col] = df[col].str.replace('\n', '<br>')

This method uses regex by default.