str.slice function is used to get the substring of the column in pandas dataframe python. Let’s see an Example of how to extract a substring from column of pandas dataframe and store it in new column.
Substring of column in pandas python:
Substring of column in pandas data frames can be achieved by using str.slice function. Let’s see with an example. First let’s create a data frame
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:
We will be using str.slice function on the column to get the substring. Here we will be taking first 7 letters as the substring on State column and will be naming the column as state_substring as shown below
''' Get the substring in pandas ''' df1['state_substring'] =df1.State.str.slice(0, 7) print(df1)
so the resultant dataframe will be
Only first 7 letters are chosen as substring and stored in separate column as shown above.