user5826447 user5826447 - 8 days ago 5
Python Question

altering values in a pandas df based on column value length

I am trying to change some incorrect values in a df. If the values in the 'subject' column are 3 characters long, they should have a '0' added to them to make them correct. The below code doesn't work, but kind of shows what I'm trying to do. Any help would be appreciated.

df.loc[df['subject'].len() == 3, 'subject'] = '0' + the current value

Answer

I'd use .str.zfill() method:

df.subject = df.subject.str.zfill(4)

alternatively, you can do this:

df.loc[df['subject'].str.len() == 3, 'subject'] = '0' + df['subject']

but i would choose the first option