Skip to content
Advertisement

Number Formatting in DataFrame

How can I format a subset of a DataFrame according to a custom formatting logic?

Before:

Country Last Previous Abs. Change
0 United States 8.60 8.30 0.30
1 Japan 2.50 2.50 0.00
2 China 2.00 2.10 -0.10
3 United Kingdom 9.10 9.00 0.10
4 Euro Area 8.10 7.40 0.70

After:

Country Last Previous Abs. Change
0 United States 8.6 8.3 30 bp
1 Japan 2.5 2.5 0 bp
2 China 2.0 2.1 -10 bp
3 United Kingdom 9.1 9.0 10 bp
4 Euro Area 8.1 7.4 70 bp

Advertisement

Answer

Original Data:

df = pd.DataFrame({'Country': ['United States', 'Japan','China','United Kingdom','Euro Area'],
                    'Last': [8.60, 2.50, 2.00, 9.10, 8.10],
                    'Previous': [8.30, 2.50, 2.10, 9.00, 7.40],
                    'Abs. Change': [0.30, 0.00, -0.10, 0.10, 0.70]})

1 decimal rounding

df[['Country', 'Last', 'Previous']] = df[['Country', 'Last', 'Previous']].round(1)

Add bp

df['Abs. Change'] = df['Abs. Change'].apply(lambda x: str(x) + ' bp')

Result

print(df)

         Country  Last  Previous Abs. Change
0   United States   8.6       8.3      0.3 bp
1           Japan   2.5       2.5      0.0 bp
2           China   2.0       2.1     -0.1 bp
3  United Kingdom   9.1       9.0      0.1 bp
4       Euro Area   8.1       7.4      0.7 bp
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement