Right pad in pandas dataframe python

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

  • Right padding of a string column in pandas python.

 

Syntax of right padding in pandas:

dataframe.column.str.pad(width, side=’right’, 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

Right pad in pandas dataframe python 1

 

Right padding of a string column in pandas python:

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

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

Right pad in pandas dataframe python 2

p right pad in pandas dataframe python                                                                                                               n right pad in pandas dataframe python