Anant Kumar
Anant Kumar

Reputation: 641

Set Decimal Point Precision in a Pandas Dataframe

I have a dataframe which looks like this -

df

    A   B
0   1   2
1   2   3
2   3   4

I'd like to create a function that could do the following -

df.numberformat['A']='0.2f'

I know this can be done using pandas.set_option('display.float_format', '{:.2f}'.format). However I'd like to create a class that inherits pandas.DataFrame and create a functionality as mentioned before.

Any ideas.

Upvotes: 0

Views: 7461

Answers (2)

Anant Kumar
Anant Kumar

Reputation: 641

Used some help from the links provided by @droebi and wrote a CustomDataFrame class that inherits the pandas dataframe and created a custom numberformat method that could format the columns as per user request.

class CustomDataFrame(pd.DataFrame):          
    def __init__(self,df):
        super().__init__(df)
        self.numberformat=self.format
        
    def format(self, column, format_):
        return pd.DataFrame(self[column]).astype(float).applymap(format_.format)

The a object below is a dataframe but of class CustomDataFrame -

df=pd.DataFrame({"A":[1,2,3],"B":[2,3,4]})
a=CustomDataFrame(df)
a.numberformat('A','{:,.2f}')

I couldn't use the Styler object as I needed the formatting to be kept and the formatted data to be used further in the code.

Upvotes: 0

kinshukdua
kinshukdua

Reputation: 1994

Pandas has a table visualization DataFrame.style attribute which returns a Styler object. the format function has a precision argument to specifically help formatting floats.

So all you have to do is

df.style.format(precision=0)

You can also pass in the specifier directly if you wish to

 df.style.format('{:.0f}')

Upvotes: 2

Related Questions