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.
.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).
Series.str.ljust(width, fillchar=’ ‘)
Series.str.rjust(width, fillchar=’ ‘)
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.
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.
As shown in the output image, the team string now has “*” prefixed to the old string.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.