Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply rows of one column after groupby in pandas?

Tags:

python

pandas

I have a pandas dataframe in the following format:

 user  percent 
  x      0.2
  x      0.5
  x      0.8
  y      0.1
  y      0.6
  y      0.2
  y      0.6

I am trying to multiply the percents in the rows for each user.

In the example, the result for x will be 0.2*0.5*0.8 = 0.08

The dataframe should therefore look like that:

user     result
  x      0.08
  y      0.0072

How to get my expected output?

like image 225
Lili Avatar asked Jan 23 '18 16:01

Lili


People also ask

How do you count after Groupby pandas?

Use count() by Column Name Use pandas DataFrame. groupby() to group the rows by column and use count() method to get the count for each group by ignoring None and Nan values. It works with non-floating type data as well.

How do I multiply multiple columns in pandas?

DataFrame. multiply() Method. This method is used to multiply two dataframe columns, we need to define the column which has to be multiplied inside square brackets with our dataframe like df[col], and then multiply() method will take another column with whom we want to multiply.

How do you multiply all rows in a DataFrame?

First of all, create a data frame with multiple rows and a data frame with single row. Then, use mapply function to multiply row values in the data frame having multiple rows with single row data frame.


2 Answers

groupby + prod.

df.groupby('user', as_index=False).prod()

  user  percent
0    x   0.0800
1    y   0.0072

Or, using apply + np.prod -

df.groupby('user', as_index=False).apply(np.prod)

  user  percent
0    x   0.0800
1    y   0.0072
like image 101
cs95 Avatar answered Sep 28 '22 09:09

cs95


cumprod + iloc[-1]

df.groupby('user').percent.apply(lambda x : x.cumprod().iloc[-1])
Out[532]: 
user
x    0.0800
y    0.0072
Name: percent, dtype: float64
like image 34
BENY Avatar answered Sep 28 '22 08:09

BENY