You can use str.zfill:

#numeric as string
df = pd.DataFrame({'Section':['1', '2', '3', '4', 'SS', '15', 'S1', 'A1']})

df['Section'] = df['Section'].str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1

If mixed numeric with strings first cast to string:

df = pd.DataFrame({'Section':[1, 2, 3, 4, 'SS', 15, 'S1', 'A1']})

df['Section'] = df['Section'].astype(str).str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1
Answer from jezrael on Stack Overflow
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ pandas โ€บ string โ€บ python-pandas-string-exercise-3.php
Pandas: Add leading zeros to the integer column in a pandas series and makes the length of the field to 8 digit - w3resource
Original dataframe: amount 0 10 1 250 2 3000 3 40000 4 500000 Add leading zeros: amount 0 00000010 1 00000250 2 00003000 3 00040000 4 00500000 ... Write a Pandas program to format an integer series by adding leading zeros so that each value becomes 8 digits long.
๐ŸŒ
DataScience Made Simple
datasciencemadesimple.com โ€บ home โ€บ add leading zeros in python pandas (preceding zeros in data frame)
Add leading zeros in Python pandas (preceding zeros in data frame) - DataScience Made Simple
October 17, 2024 - # create dataframe import pandas as pd d = {'Col1' : [1,200,3000,40000]} df=pd.DataFrame(d) df ยท Which results in a dataframe as shown below. ## Add leading zeros to the integer column in Python df['Col2']=df['Col1'].apply(lambda x: '{0:0>10}'.format(x)) df
Discussions

pandas - Python add a leading zero to column with str and int - Stack Overflow
Hello I want to add a leading zero in my current column with str and int but I do not know how. I only want to add leading zeros to the numbers ex: not A111. The data is imported from a csv file.... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Add Leading Zeros to Strings in Pandas Dataframe - Stack Overflow
I have a pandas data frame where the first 3 columns are strings: ID text1 text 2 0 2345656 blah blah 1 3456 blah blah 2 541304 blah ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
pandas question: how can I preserve leading zeros after saving to a CSV?
The problem is: when I save it to a CSV, the leading zeros in one of my columns get dropped. How do you know? For instance, if you are opening the file in Excel, it might be that Excel is doing this trimming. Minimal example: >>> import pandas as pd >>> >>> # make a sample dataframe with numerical data >>> df = pd.DataFrame({'x': [1, 2, 300, 400, 500]}) >>> df.head() x 0 1 1 2 2 300 3 400 4 500 >>> >>> # convert the int column to str type >>> df['x'] = df['x'].astype(str) >>> >>> # add zero padding >>> df['x'] = df['x'].apply(lambda x: x.zfill(3)) >>> df.head() x 0 001 1 002 2 300 3 400 4 500 >>> >>> # save csv >>> df.to_csv('test.csv') After exiting python, I can check out the csv from terminal: $ cat test.csv ,x 0,001 1,002 2,300 3,400 4,500 the leading zeros are there. But Excel would remove them, assuming the column was numerical. So that might be your new problem to solve :) how to keep leading zeros within the CSV file itself? I bet they already ARE in the file itself I feel like I'm so close Maybe closer than you think, i.e. already done haha More on reddit.com
๐ŸŒ r/learnpython
15
5
February 17, 2021
python pandas add leading zero to make all months 2 digits - Stack Overflow
How can I add a leading zero so i have a minimum of double digits. Week product quantity Month 0 201301 coke 1.5 1 1 201302 fanta 1.7 2 2 2013... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas and leading zeros with int
r/learnpython on Reddit: Pandas and Leading Zeros with INT
January 7, 2021 -

I am working on a script where I am taking data and inserting it into a database.

The easiest way for me to do this was putting it in pandas dataframes and then loading it into the DB.

One column will have integers like social security numbers were they are always 9 digits and sometimes have leading 0's. All 9 digits are always expected whether its 123456789 or 012345678.

It seems to me that I can keep the leading 0 if I set the dtype to str. However as soon as it gets set to int it drops the leading zero.

Now the database is expecting INT so I believe what is happening as it is loaded into the database pandas is doing a conversion from str to int for the DB and dropping the leadign zero.

Relevant part of script:

    data = pd.read_csv(f'./Data/csv/{filename}', encoding = 'utf-16', index_col=False)

    data = data.replace({np.nan: None})

    conn = pyodbc.connect('DRIVER={SQL Server};'
                          f'SERVER={server};'
                          f'DATABASE={database};'
                          f'UID={user};'
                          f'PWD={password}')

    cursor = conn.cursor()

    for row in data.itertuples(index=False):
        cursor.execute(eval(query), row)

    cursor.commit()
    cursor.close()
    conn.close()

Is there a way to retain or FILL the leading 0 spaces? (zfill does not work for INT as far as I know)

Or would it be better to change the schema of the DB to varchar or something even though that would be a PITA?

Thanks!

๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ pandas โ€บ string โ€บ python-pandas-string-exercise-4.php
Pandas: Add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit - w3resource
Write a Pandas program to process a character column to add leading zeros dynamically based on the current length of each string. ... PREV : Add Leading Zeros to Integers.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.Series.str.zfill.html
pandas.Series.str.zfill โ€” pandas 3.0.5 documentation
Note that 10 and NaN are not strings, therefore they are converted to NaN. The minus sign in '-1' is treated as a special character and the zero is added to the right of it (str.zfill() would have moved it to the left).
๐ŸŒ
YouTube
youtube.com โ€บ pygpt
add leading zeros pandas - YouTube
Instantly Download or Run this code online at https://codegive.com Certainly! Adding leading zeros to numerical values in a pandas DataFrame can be useful, e...
Published: January 11, 2024
Views: 24
Find elsewhere
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.str.zfill.html
pandas.Series.str.zfill โ€” pandas 3.0.5 documentation - PyData |
Note that 10 and NaN are not strings, therefore they are converted to NaN. The minus sign in '-1' is treated as a special character and the zero is added to the right of it (str.zfill() would have moved it to the left).
๐ŸŒ
YouTube
youtube.com โ€บ pygpt
add leading zeros in python pandas - YouTube
Instantly Download or Run this code online at https://codegive.com Adding Leading Zeros in Python Pandas: A TutorialIn data manipulation and analysis, it's c...
Published: January 11, 2024
Views: 11
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-pandas-int-to-string-with-leading-zeros
Python | pandas int to string with leading zeros - GeeksforGeeks
July 23, 2025 - In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed. In this article, we will discuss How we can convert pandas int to string ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ pandas question: how can i preserve leading zeros after saving to a csv?
r/learnpython on Reddit: pandas question: how can I preserve leading zeros after saving to a CSV?
February 17, 2021 -

EDIT: Solved! Well actually there wasn't really anything to solve lol I'm just a noob and a half. To those interested in the answer, please see the reply by u/spez_edits_thedonald. Thank you to everyone who helped. Wow i love this sub so much

I have a gigantic pandas dataframe (8 million rows) and I need to upload it's contents to our platform at work. Side note: I'm kind of excited because no one in my office has ever done this on this scale, so I'm hoping I can impress my bosses.

Unfortunately, there is a file size limit of 2 MB per upload into our platform. I can't use an API, which means I don't have the option of doing this row by row directly from the pandas dataframe itself (wish I could, that would make this a lot easier). This also means that I'm not really able to manipulate the data using pandas between file upload iterations... at least I dont think so? My plan is to slice my gigantic dataframe up into a bunch of smaller CSV files (I'm pretty sure I can figure out how to do this part myself) and then do some browser automation with selenium. Selenium sounds agonizing but honestly I'm cool with letting this run all night and then waking up tomorrow to see the finished product.

The problem is: when I save it to a CSV, the leading zeros in one of my columns get dropped. This is stopping me dead in my tracks. I can't figure out how to preserve leading zeros in the CSV itself. I know how to add leading zeros in a pandas df by doing:

df['my_column'] = df['my_column'].apply(lambda x: x.zfill(5)) but this doesn't help me once it's saved to the CSV

Here is an example of my dataframe:

color shape identifier
0 blue circle 06432
1 red square 01245
2 green triangle 08750
3 yellow oval 12350
4 orange rectangle 19862

This data is good and ready to go but when I save it to a csv by doing df.to_csv('saved_df.csv') it becomes this:

color shape identifier
0 blue circle 6432
1 red square 1245
2 green triangle 8750
3 yellow oval 12350
4 orange rectangle 19862

Please note how the leading zeros in df['identifier'] are dropped

Does anyone know how to keep leading zeros within the CSV file itself? Ultimately I need the leading zeros to be there after i do df.to_csv('saved_df.csv') and when I'm uploading the CSV to our platform.

I tried doing df['identifier'] = df['identifier'].astype(str) and then saving it to a csv but it seems like that column gets converted back to integers once it is saved to the csv.

I feel like I'm so close to impressing my bosses with this sheer amount of productivity. Any help would be greatly appreciated. Thank you, kind pythonistas of reddit :)

๐ŸŒ
Arab Psychology
scales.arabpsychology.com โ€บ home โ€บ how to easily add leading zeros to strings in pandas
How To Easily Add Leading Zeros To Strings In Pandas
November 30, 2025 - It operates efficiently across entire Series, abstracting away the complexities of iterative Python loops and providing a highly optimized solution native to the Pandas library structure. While str.zfill() is excellent for simple cases where only zeros are needed, complex data formatting scenarios, particularly those requiring conditional padding or integration with dynamic formatting techniques, often benefit from a more versatile approach.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-add-leading-zeros-to-a-number-in-python
How to Add leading Zeros to a Number in Python - GeeksforGeeks
March 24, 2023 - 4 min read Python | pandas int to string with leading zeros ยท In Python, When it comes to data manipulation and data analysis, Panda is a powerful library that provides capabilities to easily encounter scenarios where the conversion of integer to string with leading zeros is needed.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.str.pad.html
pandas.Series.str.pad โ€” pandas 3.0.6 documentation - PyData |
Pad strings in the Series/Index up to width ยท This function pads strings in a Series or Index to a specified width, filling the extra space with a character of your choice. It provides flexibility in positioning the padding, allowing it to be added to the left, right, or both sides.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ pandas-docs โ€บ stable โ€บ reference โ€บ api โ€บ pandas.Series.str.pad.html
pandas.Series.str.pad โ€” pandas 3.0.3 documentation
Pad strings in the Series/Index up to width ยท This function pads strings in a Series or Index to a specified width, filling the extra space with a character of your choice. It provides flexibility in positioning the padding, allowing it to be added to the left, right, or both sides.