haneulkim
haneulkim

Reputation: 4928

multiply all values in a column python pandas

I am using pandas 1.14 and python 3.8

Given a dataframe:

Id      A      B
1       3      4
2       3      4
3       1      2
4       4      3

If I want to sum all values in A column I would simply to sum(df["A"]) How can I replace sum -> multiplication?

what I want is multiply(df["A"]) which would return 3 x 3 x 1 x 4 = 36.

Thanks in advance!

Upvotes: 1

Views: 550

Answers (4)

U13-Forward
U13-Forward

Reputation: 71580

Try cumprod:

print(df['A'].cumprod())

Output:

0     3
1     9
2     9
3    36
dtype: int64

cumprod stands for "cumulative product", it multiplies the values with each other cumulatively.

Upvotes: 1

wwnde
wwnde

Reputation: 26676

Lets try

 df.loc['prod','A']=df.A.prod(0)

Upvotes: 0

Chris
Chris

Reputation: 16147

This should work

df.A.product()

Upvotes: 3

haneulkim
haneulkim

Reputation: 4928

numpy.prod(df["A"])

seems to do the trick! However if there is pandas way of doing it I would love to know!

Upvotes: 0

Related Questions