In This Section we will be focusing on how to remove the last N characters of the column in pandas. we have also explored two ways to remove or delete the last N Characters of the column in pandas with an example for each.
- Remove or delete last n characters from right of the column in pandas python in a roundabout way.
- Remove or delete last n characters of the column in pandas python using slice() function with stop 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 Last N Character of the column in pandas:
Method1:
Remove Last n character of the column in pandas can be done in by subsetting and deleting Last N Characters as shown below
#### Remove last n character of the column in pandas #Method 1 df['Description'] = df['Description'].str[:-4] df
Result:
Method 2:
Removing last n character of the column in pandas can be done by using slice() function with stop parameter as -4 which deletes or removes last 4 characters as shown below
#### Remove last n character of the column in pandas #Method 2 df['Description'] = df['Description'].str.slice(stop=-4) df
Result: