TransWikia.com

Vector implementation of product of column vectors in python

Stack Overflow Asked by Anish on December 31, 2020

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]

3 Answers

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])

Correct answer by Pygirl on December 31, 2020

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]

Answered by Luis Díaz on December 31, 2020

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]

Answered by Amir saleem on December 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP