Home >Backend Development >Python Tutorial >How to Add Leading Zeros to String Columns in a Pandas DataFrame?

How to Add Leading Zeros to String Columns in a Pandas DataFrame?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 19:38:02602browse

How to Add Leading Zeros to String Columns in a Pandas DataFrame?

Leading Zeros for Pandas DataFrame Strings

To add leading zeros to string columns in a Pandas DataFrame, you can use the following code snippet:

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

This method uses the zfill() function from the str attribute, which allows you to specify the desired width of the string. In this case, we are adding 15 leading zeros to the ID column.

Example:

Consider the following DataFrame with string columns:

ID text1 text 2
2345656 blah blah
3456 blah blah
541304 blah blah
201306 hi blah
12313201308 hello blah

Using the zfill() method, we can add leading zeros to the ID column:

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

This will result in the following DataFrame:

ID text1 text 2
000000002345656 blah blah
000000000003456 blah blah
000000000541304 blah blah
000000000201306 hi blah
000012313201308 hello blah

Additional Notes:

  • The zfill() method can also be used to add zeros to the end of a string by specifying a negative width value.
  • You can also use the {0:0>15} formatting syntax to add leading zeros, as shown in the question. However, the str.zfill() method is more concise and efficient.

The above is the detailed content of How to Add Leading Zeros to String Columns in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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