How to remove decimal points in pandas

Question:

I have a pandas data frame, df, which looks like this:

Cut-off             <=35   >35                   
Calcium              0.0   1.0
Copper               1.0   0.0
Helium               0.0   8.0
Hydrogen             0.0   1.0

How can I remove the decimal point so that the data frame looks like this:

Cut-off             <= 35  > 35                   
Calcium              0     1
Copper               1     0
Helium               0     8
Hydrogen             0     1

I have tried df.round(0) without success.

Asked By: Amani

||

Answers:

You have a few options…

1) convert everything to integers.

df.astype(int)
          <=35  >35
Cut-off            
Calcium      0    1
Copper       1    0
Helium       0    8
Hydrogen     0    1

2) Use round:

>>> df.round()
          <=35  >35
Cut-off            
Calcium      0    1
Copper       1    0
Helium       0    8
Hydrogen     0    1

but not always great…

>>> (df - .2).round()
          <=35  >35
Cut-off            
Calcium     -0    1
Copper       1   -0
Helium      -0    8
Hydrogen    -0    1

3) Change your display precision option in Pandas.

pd.set_option('precision', 0)

>>> df
          <=35  >35
Cut-off            
Calcium      0    1
Copper       1    0
Helium       0    8
Hydrogen     0    1 
Answered By: Alexander

Since pandas 0.17.1 you can set the displayed numerical precision by modifying the style of the particular data frame rather than setting the global option:

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
df 

enter image description here

df.style.set_precision(2)

enter image description here

It is also possible to apply column specific styles

df.style.format({
    'A': '{:,.1f}'.format,
    'B': '{:,.3f}'.format,
})

enter image description here

Answered By: joelostblom

You can alternatively use this code as well if you do not want decimals at all:

df['col'] = df['col'].astype(str).apply(lambda x: x.replace('.0',''))
Answered By: milad bahari javan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.