Open In App
Related Articles

How to remove random symbols in a dataframe in Pandas?

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will see how to remove random symbols in a dataframe in Pandas.

Method 1: Selecting columns

Syntax: dataframe[columns].replace({symbol:},regex=True)

First, select the columns which have a symbol that needs to be removed. And inside the method replace() insert the symbol example replace(“h”:””)

Python3




import pandas as pd
 
 
df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': ['f;', 'd:', 'sda;sd'],
                   'D': ['s', 'd;', 'd;p'],
                   'E': [5, 3, 6],
                   'F': [7, 4, 3]})
 
print(df)
 
cols_to_check = ['C', 'D', 'E']
print(df[cols_to_check])
 
df[cols_to_check] = df[cols_to_check].replace({';': ''}, regex=True)
print(df)


Output:

Method 2: Using dataframe.iloc

Syntax:

dataframe.iloc[].replace({character},regex=True)

In this method, you use dataframe.iloc[] to change the symbols.

Python3




import pandas as pd
 
df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': ['f;', 'd:', 'sda;sd'],
                   'D': ['s', 'd;', 'd;p'],
                   'E': [5, 3, 6],
                   'F': [7, 4, 3]})
 
print(df)
 
cols_to_check = ['C', 'D', 'E']
print(df.iloc[[0, 2]])
 
df.iloc[[0, 2]] = df.iloc[[0, 2]].replace({';': ''}, regex=True)
print(df)


Output:

Method 3: Using dataframe.loc[]

Syntax:

dataframe.loc[].replace({character},regex=True)

Python3




import pandas as pd
 
 
df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': ['f;', 'd:', 'sda;sd'],
                   'D': ['s', 'd;', 'd;p'],
                   'E': [5, 3, 6],
                   'F': [7, 4, 3]})
 
print(df)
 
cols_to_check = ['C', 'D', 'E']
print(df.loc[:, cols_to_check])
 
 
df.loc[:, cols_to_check] = df.loc[
  :, cols_to_check].replace({';': ''}, regex=True)
print(df)


Output:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 Jun, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials