Home »
Python »
Python Programs
Remove first x number of characters from each row in a column of a Python DataFrame
Given a Pandas DataFrame, we have to remove first x number of characters from each row in a column.
By Pranit Sharma Last updated : September 29, 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.
A 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 have a DataFrame of bank details of a few people which contains some required columns. In the Bank account column, we have an unwanted string of 5 characters in each value, we need to remove this unwanted string from each row.
Removing first x number of characters from each row in a column of DataFrame
For this purpose, we will use the concept of string slicing along with the specified DataFrame's column using the .str[5:]. Here, 5 is the value of x. And, then update the column value with this result.
Let us understand with the help of an example,
Python program to remove first x number of characters from each row in a column of dataframe
# Importing pandas package
import pandas as pd
# Creating two dictionaries
d1 = {
'Name':['Rohan','Mohit','Naresh','Varun'],
'Acc_No':['xxxxx9898','xxxxx9792','xxxxx2782','xxxxx9122']
}
# Creating DataFrames
df = pd.DataFrame(d1)
# Display the DataFrames
print("Original DataFrame 1:\n",df,"\n\n")
# Removing string from each row
df['Acc_No'] = df['Acc_No'].str[5:]
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »