Reputation: 33
Is there any vector implementation of multiplying columns in 2D-data to generate a single column which contains the product of all column values in python? For example [[1,2,3],[2,1,4],[1,7,3],[4,1,1]] to [6, 8, 21, 4]
Upvotes: 2
Views: 51
Reputation: 72
You have the option of using reduce from functools. This function "reduce" a list applying an operation in an accumulative way. The operation is going to be the product, implemented as a lambda, which is always more pythonic.
from functools import reduce
x = [[1,2,3],[2,1,4],[1,7,3],[4,1,1]]
y = [reduce(lambda x,y: x*y, element) for element in x] #=[6, 8, 21, 4]
Upvotes: 0
Reputation: 1496
Try product
from pandas
L = [[1,2,3],[2,1,4],[1,7,3],[4,1,1]]
pd.DataFrame(L).product(axis=1).to_list()
# [6, 8, 21, 4]
Upvotes: 1
Reputation: 13349
Try np.multiply
or np.prod
a = np.array([[1,2,3],[2,1,4],[1,7,3],[4,1,1]])
np.multiply.reduce(a, axis=1)
OR
np.prod(a, axis=1)
array([ 6, 8, 21, 4])
Upvotes: 2