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 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!