AnswerBun.com

Vector implementation of product of column vectors in python

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]

Stack Overflow Asked by Anish on December 31, 2020

3 Answers

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!

Related Questions

How Can I Not Double Count Rows And Objects In My Query?

3  Asked on November 22, 2021 by ziegler199

       

Login with active directory

0  Asked on November 20, 2021 by artisan

       

External CSS not linking for all elements

1  Asked on November 20, 2021 by stratos-la

   

Why is ‘u{1D11E}’.charAt(0) not equal to ‘u{1D11E}’?

2  Asked on November 20, 2021 by json-prime

     

E: Unable to locate package python3-boto3

2  Asked on November 20, 2021 by rosi-darmawati

       

x and o in tic tac toe keeps alternating

0  Asked on November 20, 2021 by channee-mathmath

     

Remove using a button

2  Asked on November 20, 2021 by gastn

   

remove 0 and add ‘ ‘ in every number in pandas

1  Asked on November 20, 2021 by spt-hsb

   

nav-tabs doesn’t change on click

0  Asked on November 20, 2021 by beureu

     

Stick element on bottom on page scroll

3  Asked on November 20, 2021

         

Exchange each 100 in a dataframe for another value

1  Asked on November 20, 2021 by tarik-benrabah

     

GraphQL & Using a nested subscribe function

1  Asked on November 20, 2021 by u-rogel

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.