In This Section we will be focusing on how to replace the Last N character of the column in pandas, we have also explored two ways to replace the Last N Characters of the column in pandas with an example for each.
- Replace Last n characters from right of the column in pandas python can be replaced in a roundabout way.
- Replace 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
Replace Last N Character of the column in pandas:
Method 1:
Replace last n character of the column in pandas can be done in by removing the last N character and appending the required string as shown in the example below. We have replaced last 4 characters with the string “Quarter”
#### Replace last n character of the column in pandas df['Description'] = df['Description'].str[:-4] + "Quarter" df
Result:
Method 2:
Slice() function with stop parameters value -4 will remove the last 4 characters and it is replaced with ‘Quarter’ string.
### Replace last n character of the column in pandas ##Method 2 df['Description'] = df['Description'].str.slice(stop=-4) + "Quarter" df
Result: