Pandas: change printable representation of series

Viewed 36

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

2 Answers
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)

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
Related