Search code examples
pythonpandasdataframeformatseparator

Format multiple dataframe columns with the thousand separator


I was able to put the thousand separator to one column slice. How would I do that to multiple columns?

This works:

summary.iloc[:,6]=summary.iloc[:,6].map('{:,}'.format)

But this does not:

summary.iloc[:,6]=summary.iloc[:,6:].map('{:,}'.format)

Solution

  • You're looking for df.applymap:

    summary.iloc[:, 6:] = summary.iloc[:,6:].applymap('{:,}'.format)
    

    MVCE:

    df = pd.DataFrame({'Col1' : np.random.choice(10000, 10), 'Col2' :  np.random.choice(10000, 10)})
    df
    
       Col1  Col2
    0  3362  4943
    1  7296  1600
    2   222  3276
    3  8287  8913
    4   816  2211
    5  8550  9625
    6  1020  1453
    7  5635  4890
    8  4218  3150
    9  9601  4744
    
    df.iloc[:, :].applymap('{:,}'.format)
    
        Col1   Col2
    0  3,362  4,943
    1  7,296  1,600
    2    222  3,276
    3  8,287  8,913
    4    816  2,211
    5  8,550  9,625
    6  1,020  1,453
    7  5,635  4,890
    8  4,218  3,150
    9  9,601  4,744