[945] Replacing a string in all cells of a Pandas DataFrame
To replace a string in all cells of a Pandas DataFrame, we can use the str.replace()
method, which allows us to perform string replacements on each element of a column.
Here is an example:
import pandas as pd
# Create a sample DataFrame
data = {'Column1': ['abc', 'def', 'ghi', 'jkl', 'mno'],
'Column2': ['pqr', 'stu', 'vwx', 'yz', 'abc']}
df = pd.DataFrame(data)
# Replace 'ab' with 'XY' in Column1
df['Column1'] = df['Column1'].astype(str).str.replace('ab', 'XY')
# Replace 'ab' with 'XY' in Column2
df['Column2'] = df['Column2'].astype(str).str.replace('ab', 'XY')
print(df)
In this example, str.replace()
is used to replace the specified strings in each cell of the specified Columns. Adjust the column names and replacement characters based on our specific needs.
If we want to replace a string in all columns of the DataFrame, we can apply the str.replace()
method to the entire DataFrame:
# Replace 'ab' with 'XY' in all columns
df = df.apply(lambda col: col.astype(str).str.replace('ab', 'XY'))
print(df)
Adjust these examples according to the specific use case.