Home »
Python »
Python Programs
Pandas Extract Number from String
Given a pandas dataframe, we have to extract number from string.
By Pranit Sharma Last updated : October 03, 2023
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.
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.
Problem statement
Suppose we are given a DataFrame with a string-type column. These columns have some words and some numbers. We need to filter out these numbers from the entire word.
Extracting Number from String
We will use the extract() method inside which we will pass a regex (regular expression) that will filter out the numbers from the word.
Let us understand with the help of an example,
Python program to extract number from string
# Importing pandas package
import pandas as pd
# Import numpy
import numpy as np
# Creating a dictionary
d = {'A':['1amyyj',np.nan,'10autyn','100baedf','0baadc']}
# Creating DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print("Original Dataframe :\n",df,"\n")
# Extracting number
res = df.A.str.extract('(\d+)')
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »