How to Pad Strings with Leading Zeros in a Pandas Dataframe?

Barbara Streisand
Release: 2024-10-25 02:54:29
Original
870 people have browsed it

How to Pad Strings with Leading Zeros in a Pandas Dataframe?

Adding Leading Zeros to Strings in a Pandas Dataframe

Problem:

Consider the following pandas dataframe with string values in the first three columns:

        ID        text1    text 2
0       2345656     blah      blah
1          3456     blah      blah
2        541304     blah      blah        
3        201306       hi      blah        
4   12313201308    hello      blah         
Copy after login

The goal is to add leading zeros to the ID column, so it takes the following form:

                ID    text1    text 2
0  000000002345656     blah      blah
1  000000000003456     blah      blah
2  000000000541304     blah      blah        
3  000000000201306       hi      blah        
4  000012313201308    hello      blah 
Copy after login

Solution:

To achieve this, we can leverage the str attribute of the dataframe, which provides access to a variety of string manipulation methods. One such method is zfill(), which adds leading zeros to the specified width. Here's how to implement it:

<code class="python">df['ID'] = df['ID'].str.zfill(15)</code>
Copy after login

Explanation:

The str.zfill(15) method pads each ID string with zeros until its length becomes 15 characters. If the original string is already 15 characters or more, no padding is applied.

Additional Resources:

For more information on string manipulation methods in pandas, refer to the official documentation at http://pandas.pydata.org/pandas-docs/stable/text.html

The above is the detailed content of How to Pad Strings with Leading Zeros in a Pandas Dataframe?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!