Extract first n characters from left of column in pandas python

First n characters from left of the column in pandas python can be extracted in a roundabout way. Let’s see how to return first n characters from left of column in pandas python 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

Return first n character from left of column in pandas python 1

 

Extract first n Characterss from left of column in pandas:

str[:n] is used to get first n characters of column in pandas


df1['StateInitial'] = df1['State'].str[:2]
print(df1)	

str[:2] is used to get first two characters of column in pandas and it is stored in another column namely StateInitial so the resultant dataframe will be

Return first n character from left of column in pandas python 2

 

Extract first n characters from left of column in pandas python - image previous-small-11-1 on http://www.datasciencemadesimple.com                                                                                                                next Extract first n characters from left of column in pandas python