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.
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.
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.
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.
As shown in the output image, zeroes have been prefixed and length of every string in salary column is 10 now.
- Python | pandas.to_markdown() in Pandas
- Add a Pandas series to another Pandas series
- Python | Pandas Index.insert()
- Python | Pandas DatetimeIndex.inferred_freq
- Python | Pandas PeriodIndex.start_time
- Python | Pandas PeriodIndex.week
- Python | Pandas Timestamp.second
- Python | Pandas Series.asobject
- Python | Pandas str.join() to join string/list elements with passed delimiter
- Python | Pandas DataFrame.reset_index()
- Python | Pandas dataframe.notna()
- Python | Pandas PeriodIndex.weekday
- Python | Pandas Series.dt.floor
- Python | Pandas Index.get_slice_bound()
- Python | Pandas Dataframe.duplicated()
- Python | Pandas dataframe.notnull()
- Python | Pandas series.cumprod() to find Cumulative product of a Series
- Use Pandas to Calculate Statistics in Python
- Python | Pandas Timestamp.date
- Python | Pandas Timestamp.ctime
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.