Home > OS >  Dropping the first Decimal place in Pandas
Dropping the first Decimal place in Pandas

Time:07-27

I have a data frame that looks close to this

Country Year Production
United states 2000.0 4135059.0
United states 2001.0 3759340.0
United States 2002.0 4516827.0

I am trying to drop the decimal place in each column.

df.style.set_precision(0)

Did not change anything

And

df.astype(int)
df.round()

Did not fix it either.

Is there another option I am missing?

CodePudding user response:

I don't think this is the most efficient way, but you can loop through the values in the data frame and round the year. Using the parameters passed, for example round(1.1234, 2) will return the number rounded 2 to the second decimal place, and so on.

CodePudding user response:

You can use format to set precision to 0:

import pandas as pd
from io import StringIO

data = StringIO("""Country;Year;Production
United states;2000.0;4135059.0
United states;2001.0;3759340.0
United States;2002.0;4516827.0
""")

df = pd.read_csv(data, sep=';')

df.style.format(precision=0)

Alternative (change dtype to int):

df.set_index('Country').astype(int).reset_index()

Output:

         Country  Year  Production
0  United states  2000     4135059
1  United states  2001     3759340
2  United States  2002     4516827

Hope this answers you question.

  • Related