Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round while groupping by in pandas with agg function

Is there any posibilities to round the mean of C in this group by?

df.groupby('A').agg({'B':'sum', 'C':'mean'})
like image 743
pyseo Avatar asked Jan 31 '20 15:01

pyseo


People also ask

What does AGG function do in pandas?

agg() is used to pass a function or list of function to be applied on a series or even each element of series separately. In case of list of function, multiple results are returned by agg() method.

What is AGG in Groupby?

agg is an alias for aggregate . Use the alias. A passed user-defined-function will be passed a Series for evaluation. The aggregation is for each column.

What does AGG mean in pandas?

agg is an alias for aggregate . Use the alias. Functions that mutate the passed object can produce unexpected behavior or errors and are not supported. See Mutating with User Defined Function (UDF) methods for more details.

What is possible using Groupby () method of pandas?

groupby() function is used to split the data into groups based on some criteria. pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names. sort : Sort group keys.


1 Answers

You can place round after the aggregation as shown below:

df.groupby('A').agg({'B':'sum', 'C':'mean'}).round(2)

In an aggregation it is not possible to include round inside. Hence you can place round after the aggregation. It is a simple and effective way.

Round(2) will round it off to two decimal places. You can change 2 to include whatever number of decimal places you want to round off the numbers to. For eg to round off to 3 decimal places you can use .round(3) and so on.

like image 154
noob Avatar answered Sep 30 '22 20:09

noob