How to remove numbers from string terms in a pandas dataframe?

Given a pandas dataframe, we have to remove numbers from string terms.
Submitted by Pranit Sharma, on September 20, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Remove numbers from string terms in a pandas dataframe

Suppose, we have a DataFrame with multiple columns among which we have a Name column which contains the name of the person with a specific code. All the columns of this DataFrame are of string type. We need to remove this specific code part from the Name column in each value.

The string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.

We will access the Name column and we will loop over it to access its values one by one. We will check if it contains a number so that we can replace it with an empty string.

Let us understand with the help of an example,

Python code to remove numbers from string terms in a pandas dataframe

# Importing pandas package
import pandas as pd

# Creating dictionary
d = {
    'Name':['007James','Pranit9900','Tom21','Nick14','Anmol101'],
    'Age':[33,37,29,28,23],
    'Job':[1,0,1,0,1]
}

# Creating DataFrame
df = pd.DataFrame(d)

# Display Original DataFrames
print("Created DataFrame:\n",df,"\n")

# Removing numbers from Name
df['Name'] = df['Name'].str.replace('\d+', '')

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output:

Example: Remove numbers from string terms

Python Pandas Programs »



ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.