Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round a single column in pandas

Tags:

python

pandas

Is there a way to round a single column in pandas without affecting the rest of the dataframe?

>>> print(df)   item  value1  value2 0    a    1.12     1.3 1    a    1.50     2.5 2    a    0.10     0.0 3    b    3.30    -1.0 4    b    4.80    -1.0 

I have tried the following:

>>> df.value1.apply(np.round) 0    1 1    2 2    0 3    3 4    5 5    5 

What is the correct way to make data look like this:

  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 5    c       5     5.0 
like image 594
k3it Avatar asked Oct 01 '14 03:10

k3it


People also ask

How do you remove a decimal from a column in Python?

Using trunc() Function In the first program, we will make use of trunc() function and remove the decimal present in the numbers.


2 Answers

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 
like image 121
Lyndon White Avatar answered Sep 18 '22 23:09

Lyndon White


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)) 
like image 21
Reimar Avatar answered Sep 20 '22 23:09

Reimar