Left pad in pandas dataframe python

Left pad in pandas python can be accomplished by str.pad() function. let’s see how to

  • Left padding of a string column in pandas python
  • Left padding of a numeric column in pandas python

Syntax of left padding in pandas:

dataframe.column.str.pad(width, side=’left’, fillchar=’ ‘)

width: width of resulting string; additional characters will be filled with spaces.

side: {‘left’, ‘right’, ‘both’}, default ‘left’.

fillchar: additional character which is used for filling

 

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

Left pad in pandas dataframe python 1

 

Left pad of a string column in pandas python:


df1['State']=df1.State.str.pad(15,side='left',fillchar='X')
print(df1)

We will be left padding for total 15 characters where the extra left characters are replaced by “X”.

Left pad in pandas dataframe python 2

 

Left padding of numeric column in pandas python:

Numeric column should be converted into character column before left padding.

df1['Score'] = df1['Score'].astype(str)
df1['Score']=df1.Score.str.pad(4,side='left',fillchar='0')
print(df1)

We will be left padding score column with total 4 characters where the extra left characters are replaced by 0.

Left pad in pandas dataframe python 3

 

p Left pad in pandas dataframe python                                                                                                                n Left pad in pandas dataframe python