Home »
Python »
Python Programs
Extract int from string in Pandas
Learn, how to extract int from string in Python Pandas?
By Pranit Sharma Last updated : October 06, 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 data frame containing a column. This column contains string type values but these strings have some numbers in it, we need to create a new column that only extracts the entry from this column.
Extracting int from string
We know that an integer data type in programming is the value that holds whole numbers in a specific range.
For this purpose, we will use str.extract() method inside wage, we will pass a regular expression and convert the whole output into the integer value.
Let us understand with the help of an example,
Python program to extract int from string in Pandas
# Importing pandas package
import pandas as pd
# Importing numpy package
import numpy as np
# Creating a dictionary
d = {"A":['T20','I20','XUV-500','TUV-100','CD-100','RTR-180']}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display Original df
print("Original DataFrame:\n",df,"\n")
# Extracting integer from string
res = df['A'].str.extract('(\d+)').astype(int)
# Display result
print("Result:\n",res)
Output
The output of the above program is:
Python Pandas Programs »