Jason Ching Yuk
Jason Ching Yuk

Reputation: 924

Rounding up a column

I am new to pandas python and I am having difficulties trying to round up all the values in the column. For example,

Example
88.9
88.1
90.2
45.1

I tried using my current code below, but it gave me:

AttributeError: 'str' object has no attribute 'rint'

 df.Example = df.Example.round()

Upvotes: 11

Views: 31645

Answers (2)

I don't have privilege to comment. Mine is not a new answer. It is a compare of two answers. Only one of them worked as below.

  1. First I tried this https://datatofish.com/round-values-pandas-dataframe/

    df['DataFrame column'].apply(np.ceil)

It did not work for me.

  1. Then I tried the above answer

    np.ceil(df.Example).astype(int)

It worked.

I hope this will help someone.

Upvotes: 0

Ami Tavory
Ami Tavory

Reputation: 76297

You can use numpy.ceil:

In [80]: import numpy as np

In [81]: np.ceil(df.Example)
Out[81]: 
0    89.0
1    89.0
2    91.0
3    46.0
Name: Example, dtype: float64

depending on what you like, you could also change the type:

In [82]: np.ceil(df.Example).astype(int)
Out[82]: 
0    89
1    89
2    91
3    46
Name: Example, dtype: int64

Edit

Your error message indicates you're trying just to round (not necessarily up), but are having a type problem. You can solve it like so:

In [84]: df.Example.astype(float).round()
Out[84]: 
0    89.0
1    88.0
2    90.0
3    45.0
Name: Example, dtype: float64

Here, too, you can cast at the end to an integer type:

In [85]: df.Example.astype(float).round().astype(int)
Out[85]: 
0    89
1    88
2    90
3    45
Name: Example, dtype: int64

Upvotes: 20

Related Questions