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

How to display pandas DataFrame of floats using a format string for columns?

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)

yields

        cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79

but this only works if you want every float to be formatted with a dollar sign.

Otherwise, if you want dollar formatting for some floats only, then I think you'll have to pre-modify the dataframe (converting those floats to strings):

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)

yields

         cost       foo
foo $123.46 123.4567
bar $234.57 234.5678
baz $345.68 345.6789
quux $456.79 456.7890

Customized float formatting in a pandas DataFrame

In [188]: df
Out[188]:
a b c
0 1.0000 2.2460 2.0000
1 3.0000 4.4920 6.0000
2 5.0000 6.7380 10.0000

In [189]: pd.options.display.float_format = '{:,.2f}'.format

In [190]: df.apply(lambda x: x.astype(int) if np.allclose(x, x.astype(int)) else x)
Out[190]:
a b c
0 1 2.25 2
1 3 4.49 6
2 5 6.74 10

UPDATE:

In [222]: df
Out[222]:
0 1
0 3.0000 5.6000
1 1.2000 3.4560

In [223]: df.applymap(lambda x: str(int(x)) if abs(x - int(x)) < 1e-6 else str(round(x,2)))
Out[223]:
0 1
0 3 5.6
1 1.2 3.46

NOTE: be aware that .applymap() method is pretty slow as it's doing map(func, series) for each series in the DataFrame

How to format a float percent pandas dataframe column into '{:,.2f%}'

To round, but keep the column as float:

df_payers["pct"] = df_payers["pct"].round(2)

To convert to string with formatting:

df_payers["pct"] = df_payers['pct'].map("{:.2f}".format)

Format a pandas dataframe with floats and leading zeros

You can set the display float_format option as '{:09.2f}'.format:

pd.options.display.float_format = '{:09.2f}'.format
df
amount
row1 001000.50
row2 100000.78
row3 -90000.00
row4 -00900.40

But this will only change the current display. If you need to create a new column, you can use an f string:

df['newamount'] = df.amount.apply(lambda x: f'{x:09.2f}')
df
amount newamount
row1 1000.50 001000.50
row2 100000.78 100000.78
row3 -90000.00 -90000.00
row4 -900.40 -00900.40

How do I edit the string format of several Pandas DataFrame float columns?

Try this:

df = df.applymap('{:,.2%}'.format)

Pandas data frame. Change float format. Keep type float

Your dataFrame itself a type float.

Dataframe:

>>> df
Age
0 24.0
1 32.0

Check DataFrame type:

>>> df.dtypes
Age float64
dtype: object

check dtype for DataFrame column type:

>>> df.Age
0 24.0
1 32.0
Name: Age, dtype: float64

OR even check like:

>>> df['Age'].dtype.kind
'f'

The way you are using to round up double digit zeros that's correct but converting them again to float will get them remain in single zero as being float.

>>> df['Age'].map('{:,.2f}'.format)
0 24.00
1 32.00
Name: Age, dtype: object

As you are interested keeping either mimic like int values 24, 32 or 24.00 & 32.00, if you are only interested in the display of floats then you can do pd.set_option('display.float_format','{:.0f}'.format), which doesn't actually affect your data.

For Floating Format without leading zeros

>>> pd.set_option('display.float_format','{:.0f}'.format)
>>> df
Age
0 24
1 32

>>> df.dtypes
Age float64
dtype: object

For Floating Format

>>> pd.set_option('display.float_format','{:.2f}'.format)
>>> df
Age
0 24.00
1 32.00
>>> df.dtypes
Age float64
dtype: object

Alternative way

Set the display precision option:

>>> pd.set_option('precision', 0)
>>> df
Age
0 24
1 32

>>> df.dtypes
Age float64
dtype: object

Convert dataframe display float format to human readable for output display purpose only

Use the following function with display.float_format argument in pandas options method to get the desired outcome.

lambda x : '{:.2f}'.format(x) if abs(x) < 1000 else ('{:.2f} K'.format(x/1000) if abs(x) < 1000000 else ('{:.2f} M'.format(x/1000000) if abs(x) < 1000000000 else '{:.2f} B'.format(x/1000000000)))

Output:

0   10.00
1 100.00
2 1.00 K
3 10.00 K
4 100.00 K
5 1.00 M
6 10.00 M
7 100.00 M
8 1.00 B
9 10.00 B

How to format a pandas dataframe and keep original float precision values

We can use np.format_float_positional:

import numpy as np
import pandas as pd

pd.set_option('display.float_format', np.format_float_positional)

df = pd.DataFrame([
{'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}
])

print(df.to_string())

Or with an option_context

import numpy as np
import pandas as pd

df = pd.DataFrame([
{'A': 2.5e-07, 'B': 2.5e-05, 'C': 2.5e-04, 'D': 0.0001, 'E': 0.01}
])

with pd.option_context('display.float_format', np.format_float_positional):
print(df.to_string())

Both Produce:

           A        B       C      D    E
0 0.00000025 0.000025 0.00025 0.0001 0.01


Related Topics



Leave a reply



Submit