How to Apply Custom Formatting to Specific Columns in Pandas DataFrames with Floating-Point Values?

Barbara Streisand
Release: 2024-11-12 14:38:02
Original
716 people have browsed it

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

By default, pandas displays floats with precision, resulting in:

         cost
foo   123.4567
bar   234.5678
baz   345.6789
quux  456.7890
Copy after login

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

This will output:

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

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

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

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!

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