Reputation: 115
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
Upvotes: 2
Views: 1329
Reputation: 15568
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)
Upvotes: 1
Reputation: 7594
You can use ljust
for this:
df = df['ID'].astype(str).str.ljust(10, '0')
print(df)
0 1234567689
1 1234567680
2 1234567600
Upvotes: 2
Reputation: 71689
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
Upvotes: 1
Reputation: 18367
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
Upvotes: 9