1

I have a Series with different elements length like this: 1, 222, 33, 4, 55555,...

I want to make it the same length of 5, like this: 00001, 00222, 00033, 00004, 55555, ...

How can I do it? Thanks,

iceagle
  • 21
  • 2

3 Answers3

0

You could use zfill, assuming your elements are strings:

import pandas as pd

s = pd.Series(data=['1', '222', '33', '4', '55555'])

result = s.str.zfill(max(map(len, s)))
print(result)

Output

0    00001
1    00222
2    00033
3    00004
4    55555
dtype: object
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0
import pandas as pd

df = pd.Series([0] * 5) 
SciPy
  • 5,412
  • 4
  • 18
  • 18
0

You can do:

df = pd.DataFrame([1, 222, 44, 55555], columns=['Val'])
max_length = max(df['Val'].astype(str).str.len())
df['SameLen'] = df['Val'].astype(str).map(lambda x: '0' * (max_length - len(x)) + x)

Output:

    Val  SameLen
0     1    00001 
1   222    00222 
2    44    00044 
3 55555    55555 
Aryerez
  • 3,417
  • 2
  • 9
  • 17