Home >Backend Development >Python Tutorial >How to Apply Custom Formatting to Specific Columns in Pandas DataFrames with Floating-Point Values?
Custom Formatting for Float DataFrames with Pandas
Displaying pandas DataFrames with floating-point values can often benefit from custom formatting. Consider the following DataFrame:
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], columns=['cost']) print(df)
By default, pandas displays floats with precision, resulting in:
cost foo 123.4567 bar 234.5678 baz 345.6789 quux 456.7890
To format these values with currency, we can use the built-in display method:
import pandas as pd pd.options.display.float_format = '${:,.2f}'.format print(df)
This will output:
cost foo 3.46 bar 4.57 baz 5.68 quux 6.79
Selective Formatting
However, if only certain columns require custom formatting, we can pre-modify the DataFrame:
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], columns=['cost']) df['foo'] = df['cost'] df['cost'] = df['cost'].map('${:,.2f}'.format)
This customization allows for targeted formatting within the DataFrame:
cost foo foo 3.46 123.4567 bar 4.57 234.5678 baz 5.68 345.6789 quux 6.79 456.7890
The above is the detailed content of How to Apply Custom Formatting to Specific Columns in Pandas DataFrames with Floating-Point Values?. For more information, please follow other related articles on the PHP Chinese website!