Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Pandas Series.str.zfill()

  • Last Updated : 21 Sep, 2018

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 zfill() method is used to fill left side of string with zeros. If length of string is more than or equal to the width parameter, then no zeroes are prefixed. Since this is a string method, it is only applicable on series of strings and .str has to be prefixed every time before calling this method.

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Usage: This function can be used whenever dealing with numeric data stored in string format. For example, If a series contains binary numbers with different bit size. Then to do operations like 1’s compliment addition, every binary needs to be of same bit size.

Syntax: Series.str.zfill(width)

width: Maximum width of output string after prefixing zeroes.

Return type: Series with prefixed zeroes.

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: Prefixing zeroes to salary column.

In this example, a width of 8 is set and zeroes are prefixed to Salary column using zfill() method. Since the Salary column has data type of int64, it’s converted to string first using astype() method.

# importing pandas 
import pandas as pd 
# making data frame from csv at url 
# converting to string dtype
data["Salary"]= data["Salary"].astype(str)
# width of output string
width = 10
# calling method and overwriting series
data["Salary"]= data["Salary"].str.zfill(width)
# display

As shown in the output image, zeroes have been prefixed and length of every string in salary column is 10 now.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!