append 0's to dataframe string column if not specific length
I have a dataframe with a column object
.
How do I append "0" at the end of strings which are of length 4.
Column
12356
1287
23868
5643
45634
You can use str.ljust
whick takes as first argument the width
that the string should be and the character to be filled with (on right side of string) if the width is less than the specified:
df['col'] = df['col'].str.ljust(width=5, fillchar='0')
print(df)
col
0 12356
1 12870
2 23868
3 56430
4 45634
Data setup:
import pandas as pd
df = pd.DataFrame(
{'col':'12356 1287 23868 5643 45634'.split()}
,dtype=('object'))
col
0 12356
1 1287
2 23868
3 5643
4 45634
One more method can be done using list comprehension
import pandas as pd
df = pd.DataFrame(
{'col': '12356 1287 23868 5643 45634'.split()}
, dtype=('object'))
df['col'] = [i + '0' if len(i) == 4 else i for i in df['col']]
output col
:
col
0 12356
1 12870
2 23868
3 56430
4 45634