Home > Backend Development > Python Tutorial > How to Format Floating-Point Values in Pandas DataFrames Using a Format String?

How to Format Floating-Point Values in Pandas DataFrames Using a Format String?

Barbara Streisand
Release: 2024-11-12 01:20:03
Original
1080 people have browsed it

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
Copy after login

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)
Copy after login

Output:

         cost
foo   3.46
bar   4.57
baz   5.68
quux  6.79
Copy after login

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)
Copy after login

Output:

         cost       foo
foo   3.46  123.4567
bar   4.57  234.5678
baz   5.68  345.6789
quux  6.79  456.7890
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template