Get the substring of the column in pandas python

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:

Get substring of column in pandas 1

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

Get substring of column in pandas 2

Only first 7 letters are chosen as substring and stored in separate column as shown above.

 

Difference between two dates in days , weeks, Months and years in Pandas python                                                                                                                Get the substring of the column in pandas python