-1

Given the following DataFrame of pandas in Python:

ID code color
0 14563 red
1 4563 blue
2 1463 green
3 82930 red
4 903 green
5 18392 red

For the code column, I want that if the value has 4 digits or less, fill in with leading zeros until they have five digits.

ID code color
0 14563 red
1 04563 blue
2 01463 green
3 82930 red
4 00903 green
5 18392 red
Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52
Carola
  • 366
  • 4
  • 18

1 Answers1

1

try:

df['code'] = df['code'].str.zfill(5)

check: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html

you can add astype(str) if the code column is int and not str like:

 df['code'] = df['code'].astype(str).str.zfill(5)
Matteo Buffagni
  • 312
  • 2
  • 10