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.

We have explored two ways

  • Extract or return first n characters of the pandas column using subsetting
  • Extract or return first n character of the pandas column using slice() function with stop 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

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

 

Extract first n Characters from left of column in pandas:

Method 1:

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

 

 

Method 2:

Slice() function with stop parameters value 2 will extract the first 2 characters of the column as shown below.

### Extract first n character of the column in pandas
##Method 2
df1['StateInitial'] = df1['State'].str.slice(stop=2)
df1

Result:

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

 

 

                                                                                                           next Extract first n characters from left of column in pandas python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts