Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas rounding when converting the series to int

How can I round a number of decimals based on an assigned series?
My sample data is like this:

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.uniform(1,5,size=(10,1)), columns=['Results'])
df['groups'] = ['A', 'B', 'C', 'D']
df['decimal'] = [1, 0, 2, 3]

This produces a dataframe like:

   Results    decimal  groups
0  2.851325      A        1
1  1.397018      B        0
2  3.522660      C        2
3  1.995171      D        3

Next: each result number needs to be rounded the number of decimals shown in decimal. What I tried below resulted in an error of TypeError: cannot convert the series to <class 'int'>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df['new'] = df['Results'].round(df['decimal'])

I want the results like:

   Results     decimal groups new
0  2.851325      A        1   2.9
1  1.397018      B        0   1
2  3.522660      C        2   3.52
3  1.995171      D        3   1.995

>Solution :

You can pass a dict-like object to DataFrame.round to set different precision levels for different columns. So you need to transpose a single column DataFrame (constructed from Results column) twice:

df['Results'] = df[['Results']].T.round(df['decimal']).T

Another option is a list comprehension:

df['Results'] = [round(num, rnd) for num, rnd in zip(df['Results'], df['decimal'])]

Output:

   Results groups  decimal
0    2.500      A        1
1    2.000      B        0
2    2.190      C        2
3    1.243      D        3

Note that since it’s a single column, it’s decimal places is determined by the highest decimal; but if you look at the constructor of this DataFrame, you’ll see that the precisions have indeed changed:

>>> df[['Results']].to_dict('list')
{'Results': [2.5, 2.0, 2.19, 1.243]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading