JacksonCounty
JacksonCounty

Reputation: 135

Format column of integers in pandas

I want to first cast this column of integers to a string, but then have each single-digit integer formatted with 2 significant figures.

I want this:

>>> df[0].astype(str)
0          0
1          1
2          2
3          10
4          11
5          12

To become this:

>>> df[0].astype(str)
0          00
1          01
2          02
3          10
4          11
5          12

Normally I would use %.2d but I'm not sure how to do it with pandas?

Upvotes: 1

Views: 862

Answers (1)

anky
anky

Reputation: 75080

use series.str.zfill

Pad strings in the Series/Index by prepending ‘0’ characters.

df[0].astype(str).str.zfill(2)

0    00
1    01
2    02
3    10
4    11
5    12

Upvotes: 5

Related Questions