Last n characters from right of the column in pandas python can be extracted in a roundabout way. Let’s see how to return last n characters from right of column in pandas with an example.
We have explored two ways
- Extract or return last n characters of the pandas column using subset
- Extract or return last n character of the pandas column using slice() function with start parameters
First let’s create a dataframe
import pandas as pd import numpy as np #Create a DataFrame df1 = { 'State':['Arizona AZ','Georgia GG','Newyork NY','Indiana IN','Florida FL'], 'Score':[62,47,55,74,31]} df1 = pd.DataFrame(df1,columns=['State','Score']) df1
df1 will be
Extract Last n characters from right of the column in pandas:
Method 1:
str[-n:] is used to get last n character of column in pandas
df1['Stateright'] = df1['State'].str[-2:] df1
str[-2:] is used to get last two character of column in pandas and it is stored in another column namely Stateright so the resultant dataframe will be
Method 2:
Slice() function with start parameters value -2 will extract the last 2 characters of the column as shown below.
### Extract last n character of the column in pandas ##Method 2 df1['Stateright'] = df1['State'].str.slice(start=-2) df1
Result: