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