Round only some columns in pandas

I have a pandas dataframe and I would like to round only some of its columns (not all of them, not one of them). They will all be rounded to the same number of decimals.

The procedure I use at the moment looks like this:

# example dataframe
df1 = pd.DataFrame({'a':[0.1111,0.2222],'b':[0.3333,0.4444],'c':[0.5555,0.6666]})

df1
>         a       b       c
> 0  0.1111  0.3333  0.5555
> 1  0.2222  0.4444  0.6666

# I want to round columns 'a' and 'c' to two decimals
# Do it one by one
df1['a'] = df1['a'].round(2)
df1['c'] = df1['c'].round(2)

df1
>       a       b     c
> 0  0.11  0.3333  0.56
> 1  0.22  0.4444  0.67

Does anybody know if there is a way to apply round to a list of columns e.g. if I need to repeat this with multiple columns, is there a simpler way to do it instead of one by one, or instead of iterating with for [list_of_col_names]:

Answer

You can customize for each column using a dict like

In [658]: df1.round({'a': 2, 'c': 2})
Out[658]:
      a       b     c
0  0.11  0.3333  0.56
1  0.22  0.4444  0.67

Or, You could do

In [649]: cols = ['a', 'c']

In [650]: df1[cols] = df1[cols].round(2)

In [651]: df1
Out[651]:
      a       b     c
0  0.11  0.3333  0.56
1  0.22  0.4444  0.67

Leave a Reply

Your email address will not be published. Required fields are marked *