Home > front end >  pandas rounding when converting the series to int
pandas rounding when converting the series to int

Time:05-04

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    groups  decimal  
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'>

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

I want the results like:

   Results     groups decimal 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

CodePudding user response:

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]}

CodePudding user response:

Try this :

df['new']=df['Results'].copy()
df=df.round({'new': 1})
  • Related