Home  >  Article  >  Backend Development  >  How to Format Pandas DataFrame of Floats with a Custom String for Columns?

How to Format Pandas DataFrame of Floats with a Custom String for Columns?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 04:36:03586browse

How to Format Pandas DataFrame of Floats with a Custom String for Columns?

How to Display Pandas DataFrame of Floats Using a Format String for Columns?

Introduction

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.

Using pd.options.display.float_format

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

Custom Formatting for Selected Columns

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!

Statement:
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