Adding Trailing Zeros To Row Values To Make Sure There Are 10 Digits
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
Solution 1:
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
Solution 2:
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
Solution 3:
You can use ljust
for this:
df = df['ID'].astype(str).str.ljust(10, '0')
print(df)
0 1234567689
1 1234567680
2 1234567600
Solution 4:
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)
Post a Comment for "Adding Trailing Zeros To Row Values To Make Sure There Are 10 Digits"