简体   繁体   中英

Adding leading zeros for only numeric character id

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?

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.

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']})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM