Home > Article > Backend Development > How to Format Pandas DataFrame of Floats with a Custom String for Columns?
Pandas provides a convenient way to display tabular data. However, sometimes you may need to customize the display format to enhance readability or meet specific presentation requirements. This article presents methods for formatting columns containing floating-point numbers in a desired format using print() and IPython display(), without altering the original data.
To uniformly apply a desired format to all floating-point columns in a DataFrame, use the pd.options.display.float_format option. For example, to display numeric values as currency formatted strings with a dollar sign and two decimal places, you can use the following code:
import pandas as pd pd.options.display.float_format = '${:,.2f}'.format df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], columns=['cost']) print(df)
This code will produce the following output:
cost foo 3.46 bar 4.57 baz 5.68 quux 6.79
If you need different formats for different columns or want to preserve specific data types, you can modify the DataFrame itself. The following code replaces the specified column with its string representation in a custom format:
import pandas as pd 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) print(df)
The resulting output will be a DataFrame with the "foo" column formatted as currency and the "cost" column remaining as a numeric dtype:
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 Format Pandas DataFrame of Floats with a Custom String for Columns?. For more information, please follow other related articles on the PHP Chinese website!