Zero padding pandas column

Viewed 10339

I have the following dataframe, in which col_1 is type integer:

print(df)

col_1 
100
200
00153
00164

I would like to add two zeros, if the number of digits is equal to 3:

final_col
00100
00200
00153
00164

I tried with:

df.col_1 = df.col_1.astype(int).astype(str)

df["final_col"] = np.where(len(df["col_1"]) == 3, "00" + df.col_1, df.col_1 )

But it doesn't produce the expected output (it doesn't add the two digits when the condition is satisfied).

How can I solve that?

4 Answers

Another way using series.str.pad():

df.col_1.astype(str).str.pad(5,fillchar='0')

0    00100
1    00200
2    00153
3    00164

You solution should be updated to:

(np.where(df["col_1"].astype(str).str.len()==3, 
       "00" + df["col_1"].astype(str),df["col_1"].astype(str)))

But this will not work when the length of the string is less than 5 and not equal to 3, hence I recommend you to not to use this.

Use str.zfill:

df['final_col'] = df['col_1'].astype(str).str.zfill(5)

[out]

   final_col
0      00100
1      00200
2      00153
3      00164

Update, if you only want to pad where len is 3 exactly, use Series.where Thanks @yatu for pointing out:

df.col_1.where(df.col_1.str.len().ne(3),
               df.col_1.astype(str).str.zfill(5))
# after converting it to str , you can foolow up list comprehension.

df=pd.DataFrame({'col':['100','200','00153','00164']})
df['col_up']=['00'+x if len(x)==3 else x for x in df.col ]
df

###output

    col    col_up
0   100     00100
1   200     00200
2   00153   00153
3   00164   00164


    ### based on the responses in comments 
  %%timeit -n 10000
 df.col.str.pad(5,fillchar='0') 
142 µs ± 5.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)


     %%timeit -n 10000
 ['00'+x if len(x)==3 else x for x in df.col ]
21.1 µs ± 952 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

  %%timeit -n 10000
  df.col.astype(str).str.pad(5,fillchar='0')
243 µs ± 7.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Since the col column's data type is str, you can extract string using .str and use .pad() to pad the string up to width = 5 with 0 .pad(5, fillchar='0').

Check the documnetation

IN[1]:  df = pd.DataFrame({'col':['100','200','00153','00164']})
        df
Out[1]:
    col
0   100
1   200
2   00153
3   00164
In[2]:  df['final_col'] = df.col.astype(str).str.pad(5, fillchar='0')
        df
Out[2]:
    col final_col
0   100     00100
1   200     00200
2   00153   00153
3   00164   00164

Also, you can convert the data types -if the column's data type is not a string- using .astype(dtype) to convert it to string and then use .pad() on it.

Related