sdbbs
sdbbs

Reputation: 5480

Control printout of floating point decimals, in Pandas DataFrame with decimal.Decimal entries?

Consider this example:

import pandas as pd
from decimal import Decimal

my_df = pd.DataFrame(columns=["a", "b", "c"])
my_df = my_df.append({'a': 1, 'b': 3.0/7, 'c': Decimal(3.0/7)}, ignore_index=True)
print(my_df)

print("-------")

with pd.option_context('float_format', '{:.4f}'.format, 'display.expand_frame_repr', False):
  print(my_df)

This prints out:

   a         b                                                  c
0  1  0.428571  0.42857142857142854763807804374664556235074996...
-------
   a      b                                                  c
0  1 0.4286  0.42857142857142854763807804374664556235074996...

Being aware that one can control the printout of number of decimals in a float in Pandas DataFrame with pd.option_context('float_format',..., I have tried to apply the same approach to an element, which is of decimal.Decimal class. As the test code printout shows:

I'd like to keep the Decimal objects in my Pandas DataFrame, however at certain points, I'd like to print them with a smaller, limited number of decimals - like what with pd.option_context('float_format',... does for floats.

Is this controlled "truncated/rounded printout" of Decimal in a Pandas DataFrame possible - and if so, how can it be done?

Upvotes: 1

Views: 1419

Answers (1)

Richard K Yu
Richard K Yu

Reputation: 2202

I believe one way you can do this is by changing the context associated with the decimal object and recalculating the column with decimals.

Note that this seems to only work if the Decimal is calculated like Decimal(3.0) / Decimal(7). But if your decimal is complicated I think you can get around this by doing Decimal(x/y)/Decimal(1) for every decimal object in the column instead of considering each of the denominators one-by-one.

My modified code looks like:

import pandas as pd
from decimal import *


my_df = pd.DataFrame(columns=["a", "b", "c"])
my_df = my_df.append({'a': 1, 'b': 3.0/7, 'c': Decimal(3.0)/Decimal(7)}, ignore_index=True)
print(my_df)

print("-------")



#We change the precision and then reinitialize the ['c'] column with the same decimal objects.
getcontext().prec = 4
my_df['c'] = [Decimal(3.0)/Decimal(7)]

with pd.option_context('float_format', '{:.4f}'.format, 'display.expand_frame_repr', False):
  
  print(my_df)

Output:

   a         b                               c
0  1  0.428571  0.4285714285714285714285714286
-------
   a      b       c
0  1 0.4286  0.4286

Upvotes: 3

Related Questions