# select the right rows to avoid wasting time operating on longer strings shorter = df.Random.str.len() < 9 longer = ~shorter df.Random[shorter] = df.Random[shorter].str.zfill(9) df.Random[longer] = df.Random[longer].str.zfill(20)