2

If i have a data frame where max digits in each row is 10 but some IDs are less than 10 because the trailing zeros have been cut off, how do I add trailing zeros in python to make sure there are 10 digits in each row.

ID
1234567689
123456768
12345676
ID
1234567689
1234567680
1234567600
3
  • What is the dtype of that column? Commented Jun 30, 2020 at 16:04
  • 1
    Why have the trailing zeroes been cut off? Commented Jun 30, 2020 at 16:05
  • The dtype is string Commented Jun 30, 2020 at 16:06

4 Answers 4

9

You can use str.pad() which I believe works perfect for this scenario:

df['ID'] = df['ID'].str.pad(width=10,side='right',fillchar='0')

In case the dtype of the column is not string, then you can first convert it:

df['ID'] = df['ID'].astype(str).str.pad(width=10,side='right',fillchar='0')

Output:

           ID
0  1234567689
1  1234567680
2  1234567600
Sign up to request clarification or add additional context in comments.

Comments

2

You can use ljust for this:

df = df['ID'].astype(str).str.ljust(10, '0')
print(df)

0    1234567689
1    1234567680
2    1234567600

Comments

1

Another way is to use, Series.str.ljust:

df['ID'] = df['ID'].str.ljust(width=10, fillchar='0')

Result:

           ID
0  1234567689
1  1234567680
2  1234567600

Comments

1

I think f-formatting can do that

X = [1234567689, 12345, 123,]
print([f'{item:0<9}' for item in X])

This only works with Python 3.6+. The idea is to get the value and left pad 9 zeros. In Pandas you can do, the following to maintain your field as numeric

df['ID'] = df['ID'].apply(lambda x: f'{x:0<9'}).astype(int)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.