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.
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.
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.
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
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
df.style.set_precision(2)
It is also possible to apply column specific styles
df.style.format({
'A': '{:,.1f}'.format,
'B': '{:,.3f}'.format,
})
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',''))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With