Home >Backend Development >Python Tutorial >How to Format Float Columns in Pandas DataFrames?
Displaying Pandas DataFrames with Formatted Float Columns
To format float columns in a pandas DataFrame using a specific string format, several approaches can be used:
One method involves changing the display settings for floats across the entire DataFrame:
import pandas as pd # Set the format string for float values pd.options.display.float_format = '${:,.2f}'.format # Create the DataFrame df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], columns=['cost']) # Display the DataFrame print(df)
This approach applies the specified format to all float values in the DataFrame, as seen in the following output:
cost foo 3.46 bar 4.57 baz 5.68 quux 6.79
However, if you only want to format specific float columns, you will need to modify the DataFrame directly or create a copy:
import pandas as pd # Create the DataFrame df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], columns=['cost']) # Convert selected float values to formatted strings df['foo'] = df['cost'].map('${:,.2f}'.format) # Display the modified DataFrame print(df)
This approach allows for targeted formatting of selected columns, as shown below:
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 Float Columns in Pandas DataFrames?. For more information, please follow other related articles on the PHP Chinese website!