Home > Net >  How to fill a column of a pandas dataframe with an amount of digits?
How to fill a column of a pandas dataframe with an amount of digits?

Time:03-29

I have the following dataframe:

import numpy as np
import pandas as pd

df1 = pd.DataFrame({'ID_df1': [1,2,3,4],
                    'Name_df1': ['John', 'Alex', 'Alan', 'Marie'],
                    'Cod_job_df1': ['10151444', '20555', None, '40']})

I need the items in the 'Cod_job_df1' column to have a total of eleven digits. So I made the following code:

df1['Cod_job_df1'] = df1['Cod_job_df1'].apply(lambda x: x.zfill(11))

This code was working perfectly. However, when I tested in a dataframe that has a column 'Cod_job_df1' equal to None, the error code and the message appears: AttributeError: 'NoneType' object has no attribute 'zfill'

CodePudding user response:

Use str.zfill, it will ignore null values by default:

df1['Cod_job_df1'] = df1['Cod_job_df1'].str.zfill(11)

output:

   ID_df1 Name_df1  Cod_job_df1
0       1     John  00010151444
1       2     Alex  00000020555
2       3     Alan         None
3       4    Marie  00000000040
  • Related