Home > database >  Add 0 to Phone Number in a Column
Add 0 to Phone Number in a Column

Time:02-02

I have a column (phone numbers) with NAN and i need to keep al the datas so I did a

df['X'] = df['X'].fillna("0").astype(int)

My phone numbers were "float" type so I filled NA to convert to Int.

But the problem is the format of my phone numbers are wrong and i need to add a "O" before all my phone numbers.

I did this

df['X'] = df['X'].apply(lambda x: '{0:0>9}'.format(x))

But the problem is that it add extra 000's to my old NAN rows.

Is there a way to proper add 0 to my phone numbers, can I keep my NAN instead of getting them to 0

Thanks a lot.

CodePudding user response:

You can assign to a filtered version of the dataframe:

df.loc[df['A'].notna(), 'A'] = df['A'].apply(lambda x: '{0:0>9}'.format(x))

CodePudding user response:

Fill your phone first then fill nan value:

df['X'] = df['X'].astype('str').str.zfill(9).fillna('0')

CodePudding user response:

Thanks for your return, I forgot to mention, I want to add the 0 below the phone number, not at the end. Sorry

  •  Tags:  
  • Related