round a single column in pandas

For some reason the round() method doesn't work if you have float numbers with many decimal places, but this will.

decimals = 2    
df['column'] = df['column'].apply(lambda x: round(x, decimals))

Use the pandas.DataFrame.round() method like this:

df = df.round({'value1': 0})

Any columns not included will be left as is.


No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round).

>>> df.value1 = df.value1.round()
>>> print df
  item  value1  value2
0    a       1     1.3
1    a       2     2.5
2    a       0     0.0
3    b       3    -1.0
4    b       5    -1.0

Tags:

Python

Pandas