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

python pandas: how to add a value to specific rows

I have a csv where one column is a six or seven digit ID number. I want to add the number 0 to the beginning of all the IDs that have six digits. How is this possible?

for example

id

203434
405679
1049294
139294
1037912

I would like it to be

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

id

0203434
0405679
1049294
0139294
1037912

any advice appreciated.

>Solution :

You will need to convert the series dtype to string first, because integral values do not start with leading zeroes. Once you have a string you can use the Series.str.zfill method to add leading zeroes.

Try the following:

df["id"] = df["id"].astype("string").str.zfill(7)

The 7 will ensure that your id values are zero-padded on the left up to 7 characters.

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