Search code examples
pythonpandasformattingzero-padding

Format doesn't show


So I'm trying to get my month numbers to be zero padded from the left meaning {01, 02, 03, ..., 10, 11, 12}.

I thought to do so with formatting but after searching the internet I wonder if formatting really adds a zero or if I'll only see a zero when printed.

Either way, what I was trying:

months.style.format({'Test': '{:0>2}'})
print(months)

When I use this code it prints the 'Test' column without the format, why is this? I use Jupyter notebook and when I don't use the print function, he displays the data with the right format. Thank you


Solution

  • That code just changes the format in your jupyter notebook. It's similar to how formatting works in Excel. You can change the format in Excel, but it won't change the value of the cell.

    To change the format of your cell do: df.months = '0' + df.months where df is your dataframe.

    EDIT (per comment about October, November and December):

    import numpy as np
    df.months = np.where((df.months < 10), '0' + df.months, '' + df.months)