Open In App

Python | Pandas Series.str.ljust() and rjust()

Last Updated : 21 Sep, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.

Pandas .ljust() and .rjust() are Text methods used to deal with text data in series. Since these methods are applicable only on strings, .str has to be prefixed everytime before calling this method.
These methods take character or string as input parameter and prefix or suffix it to the string in the series depending upon the function used. (Suffix if ljust() and Prefix if rjust() is used).

Syntax:
Series.str.ljust(width, fillchar=’ ‘)
Series.str.rjust(width, fillchar=’ ‘)

Parameters:
width: Minimum width of output string, if width is less than the string length then nothing is concatenated
fillchar: String value, fills (Length – width) characters with the passed string.

Return type: Series with concatenated strings

Note: fillchar only takes one character, passing a string of more than one character will return an error.

To download the data set used in following examples, click here.

In the following examples, the data frame used contains data of some employees. The image of data frame before any operations is attached below.

Example #1: Use of Series.str.ljust()

In this example, a maximum width of 12 is set for team column and “_” is passed as fillchar to fill rest of the space with underscores. If String length is less than the width then “_” will be suffixed with the string.




# importing pandas module
import pandas as pd
  
# importing csv from link
# making data frame from csv
  
# width of output string
width = 12
  
# character to put 
char ="_"
  
# calling function and overwriting df
data["Team"]= data["Team"].str.ljust(width, char)
  
# display
data.head(10)


Output:
As shown in the output image, the team string now has “_” suffixed to the old string.

 
Example #2: Use of Series.str.rjust()

In this example, a maximum width of 15 is set for team column and “*” is passed as fillchar to fill rest of the space with “*”. If String length is less than the width then “*” will be prefixed with the string.




# importing pandas module
import pandas as pd
  
# importing csv from link
# making data frame from csv
  
# width of output string
width = 15
  
# character to put 
char ="*"
  
# calling function and overwriting df
data["Team"]= data["Team"].str.rjust(width, char)
  
# display
data.head(10)


Output:
As shown in the output image, the team string now has “*” prefixed to the old string.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads