0

How to add leading zeros to a int column in a data frame. I have an int column which has the time values in the format HHMMSS. Some of the time values which are after 12am have two digits. i.e 30 is supposed to be 0030, 45 is supposed tp be 0045. How do I add leading zeros to the below column

ColumnName
100012
225434
30
45
36
80200

Expected result

ColumnName
100012
225434
0030
0045
0036
80200

I tried the below code using pandas in python but it's not working

str(df.ColumnName).zfill(4)

I also tried

if(len(str(df.ColumnName))==2)
    str(df.ColumnName).zfill(4)
jpp
  • 159,742
  • 34
  • 281
  • 339
shockwave
  • 3,074
  • 9
  • 35
  • 60

2 Answers2

3

You have to take the following steps:

  1. Convert the content of the column to strings
  2. Access the content with the str accessor.
  3. Call zfill

And most importantly,

4. Reassign back to the series:


df = pd.DataFrame({'a': [1, 2, 10, 20]})
print(df)

#     a
# 0   1
# 1   2
# 2  10
# 3  20


df['a'] = df['a'].astype(str).str.zfill(4)
print(df)

#       a
# 0  0001
# 1  0002
# 2  0010
# 3  0020
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
2

Use Series built in Series.str.zfill method:

df.ColumnName.astype(str).str.zfill(4)

#0    100012
#1    225434
#2      0030
#3      0045
#4      0036
#5     80200
#Name: ColumnName, dtype: object
Psidom
  • 209,562
  • 33
  • 339
  • 356