Home > Enterprise >  Round values in column from floats to ints using Python
Round values in column from floats to ints using Python

Time:11-13

I have a dataframe, df, where I would like to round values in column from floats to ints using Python

Data

    location    a site   b site   c site
    aa          4.9000   1.72222  0.29999
    bb          5.9000   6.72222  0.46999

Note I do not wish to round down on c site 0.29999

Desired

    location    a site   b site   c site
    aa          5        2        1
    bb          6        7        1

Doing

df[list("a site", "b site", "c site")] = df[list("a site", "b site", "c site")].astype(int)

Any suggestion is appreciated

CodePudding user response:

Try with np.ceil round

df.update(df.select_dtypes(np.number).apply(np.ceil))
df
  location  asite  bsite  csite
0       aa    5.0    2.0    1.0
1       bb    6.0    7.0    1.0

CodePudding user response:

Use numpy.ceil to round up, and then convert the floats to integer using astype(int).

import numpy as np

df[["a site", "b site", "c site"]] = np.ceil(df[["a site", "b site", "c site"]]).astype(int)

>>> df

  location  a site  b site  c site
0       aa       5       2       1
1       bb       6       7       1
  • Related