Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

python - Add leading zeroes only if it begin with digit in pandas dataframe

I have a data frame column which have special characters and numbers. I want to have leading zeroes only if it begin with a digit. I need a total of 3 digits. I tried the following code:

df['input'] = df['input'].str.zfill(3)

Input:

column
1
$500
333
2
(8
?8
5
1
444

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can get what you want by:

df_merge['output'] = df_merge['input'].apply(lambda x : f'{x:0>3}' if x[0] in '0123456789' else x)

Verification

Assume the followin example to simulate the case you gave:

import pandas as pd
df_merge = pd.DataFrame({'input':['1','$500','333','2','(8','?8']})

print(df_merge['input'])

0       1
1    $500
2     333
3       2
4      (8
5      ?8
Name: input, dtype: object

now apply:

df_merge['output'] = df_merge['input'].apply(lambda x : f'{x:0>3}' if x[0] in '0123456789' else x)

print(df_merge['output'])

0     001
1    $500
2     333
3     002
4      (8
5      ?8
Name: output, dtype: object

Good Luck


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...