Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove decimal points in pandas

Tags:

python

pandas

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.

like image 756
Amani Avatar asked May 07 '16 05:05

Amani


People also ask

How do you get rid of decimal points?

Step 1: Write down the decimal divided by 1. Step 2: Multiply both top and bottom by 10 for every number after the decimal point. (For example, if there are two numbers after the decimal point, then use 100, if there are three then use 1000, etc.) Step 3: Simplify (or reduce) the Rational number.

How do I remove decimal places in Python?

Using int() method To remove the decimal from a number, we can use the int() method in Python. The int() method takes the number as an argument and returns the integer by removing the decimal part from it. It can be also used with negative numbers.


3 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 
like image 112
Alexander Avatar answered Oct 11 '22 22:10

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

like image 34
joelostblom Avatar answered Oct 11 '22 22:10

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',''))
like image 3
milad bahari javan Avatar answered Oct 11 '22 21:10

milad bahari javan