Reputation: 7446
I have a dataframe with, say, 4 rows labeled r1 through r4 and 2 columns ("c1" and "c2"). The values in this dataframe/matrix are "aij" as in (pseudo-code):
dataframe = c1 c2
r1 a11 a12
r2 a21 a22
r3 a31 a32
r4 a41 a42
I would now like to compute, in a very efficient way (think many many columns), the product of the rows.
More specifically, I would like to form a list with number of elements equal to number of columns which, as its ith element has the product of all rows:
list_ = [a11 * a21 * a31 * a41, a12 * a22 * a32 * a42]
In reality I have thousands of columns, but only around 4 rows.
I looked at dataframe's "sum(...)" function (with its "axis" argument) and it is something like that I need, but in a multiplication version. Not sure how to do this.
Upvotes: 2
Views: 4194
Reputation: 393963
IIUC you can use prod
which will calculate the product of all elements column-wise, you can then call tolist
on the result as required:
In [23]:
df = pd.DataFrame(np.arange(12).reshape(4,3), columns=list('abc'))
df
Out[23]:
a b c
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
In [26]:
df.prod()
Out[26]:
a 0
b 280
c 880
dtype: int64
In [25]:
df.prod().tolist()
Out[25]:
[0, 280, 880]
Upvotes: 2