Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas add leading zero to column with both negative and positive values

I want to add a leading zero for all rows in a column. Here is what the column looks like:

value
-1
9
10
-2

Desired output:

value
-01
09
10
-02

I tried using zfill but it doesn’t take care of the negative values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df['value'] = df['value'].astype(str).str.zfill(2)

>Solution :

Try the following :

    import pandas as pd
    
    data = {'value': [-1, 9, 10, -2]}
    df = pd.DataFrame(data)
    
    # Function to add leading zero
    def custom_zfill(x):
        if x < 0:
            return '-' + str(abs(x)).zfill(2)
        else:
            return str(x).zfill(2)
    
    df['value'] = df['value'].apply(custom_zfill)
    print(df)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading