JoeBlack JoeBlack - 4 months ago 4x
Python Question

Delete 0 in front of numbers like 06, 07, etc

The column of pandas DataFrame contains values like:

d = {'Col1' : pd.Series(['07','','10','06']),'Col2' : pd.Series([1., 2., 3.])}

I want to delete 0 in front of some integers, i.e. 07->7, 06->6, while 10 is ok.
How can I do it (including the processing of empty cels)?

I tried this code, but it gives an error
ValueError: invalid literal for int() with base 10: ''

df['Col1'] = df['Col1'].apply(lambda x: int(x))


The int() function doesn't work on empty strings, but you can easily fix it by having a fallback in case the value is falsy (and empty strings are indeed falsy):

df['Col1'] = df['Col1'].apply(lambda x: int(x or 0))

int(x) will be called when the value is non empty, and int(0) when it is (assuming you want zeros in place of empty values).