Home >Backend Development >Python Tutorial >How to Format Floating-Point Values in Pandas DataFrames Using a Format String?
Formatting Floating-Point Values in Pandas DataFrames Using a Format String
In data analysis, it may be necessary to display floating-point values in a specific format, such as currency formatting with dollar signs. While modifying the data itself is possible, it can be more efficient to preserve the original values while changing the display format.
One method to achieve this is by setting the float_format option in pd.options.display:
import pandas as pd pd.options.display.float_format = '${:,.2f}'.format
This will format all floating-point values in the DataFrame with a dollar sign and two decimal places. For example:
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo', 'bar', 'baz', 'quux'], columns=['cost']) print(df)
Output:
cost foo 3.46 bar 4.57 baz 5.68 quux 6.79
However, this approach applies the same formatting to all floating-point values. If specific columns require different formatting, it's necessary to modify the DataFrame before display.
For example, to format only the foo column with dollar signs:
df['foo'] = df['cost'] df['cost'] = df['cost'].map('${:,.2f}'.format)
Output:
cost foo foo 3.46 123.4567 bar 4.57 234.5678 baz 5.68 345.6789 quux 6.79 456.7890
By modifying the DataFrame in this manner, it retains the original floating-point values while displaying them in the desired format.
The above is the detailed content of How to Format Floating-Point Values in Pandas DataFrames Using a Format String?. For more information, please follow other related articles on the PHP Chinese website!