Remove or delete first N characters of the column in Pandas

In This Section we will be focusing on how to remove the First N characters of the column in pandas. we have also explored two ways to remove or delete the First N Characters of the column in pandas with an example for each.

  • Remove or delete First n characters from left of the column in pandas python in a roundabout way.
  • Remove or delete First n characters of the column in pandas python using slice() function with start parameters

 

Let’s Look at these cases with Example,

 

Create Dataframe:

## create dataframe 
import pandas as pd 
d = {'Day' : ['day1','day2','day3','day4'], 'Description' : ['First day of the year', 'Second day of the year', 'Third day of the year', 'FOURTH day of the YEAR']}
df=pd.DataFrame(d) 
df

Result dataframe is

Remove or delete first N character and last N character of the column in Pandas 1

 

 

Remove or delete First N Character of the column in pandas:

Method1:

 Remove First n character of the column in pandas can be done in by subsetting and deleting First N Characters as shown below

#### Remove First n character of the column in pandas
#Method 1

df['Description'] = df['Description'].str[4:]
df

Result:

Remove or delete first N character and last N character of the column in Pandas 3

 

 

Method 2:

Removing First n character of the column in pandas can be done by using slice() function with start parameter as 4 which deletes or removes First 4 characters as shown below

#### Remove First n character of the column in pandas
#Method 2

df['Description'] = df['Description'].str.slice(start=4)
df

Result:

Remove or delete first N character and last N character of the column in Pandas 3

 

                                                                                                         

 

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts