0

Say there is a series/column of three decimal values s = pd.Series([0.12, 0.1, 0.2]).

Is it possible to change the way the series prints, while keeping the same underlying data type (in this case float64)? For instance:

# Prints like this
pd.Series(['{:0.0%}'.format(i) for i in s])

0    12%
1    10%
2    20%
dtype: object
# Still works as numeric data type
s*2

0    0.48
1    0.40
2    0.80
dtype: float64

Is it easy to alter the __str__ or __repr__ of this object? Would it be possible to subclass and override this method of pd.core.series? Is there a way to make this change work inside of a pd.DataFrame?

Edit: Found the answer I was looking for here

Raisin
  • 345
  • 1
  • 9
  • 1
    check out the `style` (display) formatting options in the answers in the linked post. pandas has a ton of options for customizing the way a specific dataframe is displayed: https://pandas.pydata.org/docs/user_guide/style.html – Michael Delgado Sep 11 '22 at 18:10

2 Answers2

1
import pandas as pd

s = pd.Series([0.12, 0.1, 0.2])

with pd.option_context('display.float_format', '{:0.0%}'.format):
    print(s)
mahdilamb
  • 535
  • 3
  • 11
1

You can use pandas.set_option:

import pandas as pd

pd.set_option('display.float_format','{:0.0%}'.format)

s = pd.Series([0.12, 0.1, 0.2])

print(s*2)

Output:

0   24%
1   20%
2   40%
dtype: float64
Shahab Rahnama
  • 982
  • 1
  • 7
  • 14