I know how to add leading zeros for all values in pandas column. But my pandas column 'id' involves both numeric character like '83948', '848439' and Alphanumeric character like 'dy348dn', '494rd7f'. What I want is only add zeros for the numeric character until it reaches to 10, how can we do that?
CodePudding user response:
I understand that you want to apply padding only on ids that are completely numeric. In this case, you can use isnumeric()
on a string (for example, mystring.isnumeric()
) in order to check if the string contains only numbers. If the condition is satisfied, you can apply your padding rule.
CodePudding user response:
You can use a mask with str.isdigit
and boolean indexing with str.zfill
:
mask = df['col'].str.isdigit()
df.loc[mask, 'col'] = df.loc[mask, 'col'].str.zfill(10)
Output:
col
0 0000083948
1 0000848439
2 dy348dn
3 494rd7f
Used input:
df = pd.DataFrame({'col': ['83948', '848439', 'dy348dn', '494rd7f']})