Pandas replace function - insert pad 0 to 3 numbers

Viewed 41

in Pandas (df), a column with following strings. looking to pad 0 when number within string are <100

Freq
XXX100KHz
XYC200KHz
YYY80KHz
YYY50KHz

to:

Freq
XXX100KHz
XYC200KHz
YYY080KHz
YYY050KHz

following function doesn't work, as \1 then 0 won't work as \10 doesn't exist.

df.replace({'Freq':'^([A-Za-z]+)(\d\d[A-Za-z]*)$'},{'Freq':r'\1**0**\2'},regex=True, inplace=True)
1 Answers

Try:

df["Freq"] = df["Freq"].str.replace(
    r"(?<=\D)\d{1,2}(?=KHz)",
    lambda g: "{:0>3}".format(g.group()),
    regex=True,
)
print(df)

Prints:

        Freq
0  XXX100KHz
1  XYC200KHz
2  YYY080KHz
3  YYY050KHz
Related