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.
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']) print(df1)
df1 will be
Extract Last n characters from right of the column in pandas:
str[-n:] is used to get last n character of column in pandas
df1['Stateright'] = df1['State'].str[-2:] print(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