assume you have a pandas dataframe as follows:
x = pd.DataFrame(data={ 'x1': [np.array([1,1,1]), np.array([1,2,6])], 'x2': [np.array([2,3,2]), np.array([3,4,7])] }) I'm looking to add a new column to this dataframe, which should contain the dot product of x1 and x2, i.e. my output table should look like:
x1 | x2 | result [1,1,1] | [1,2,6] | 9 (dot product of [1,1,1] and [1,2,6]) [2,3,2] | [3,4,7] | 32 (dot product of [2,3,2] and [3,4,7]) How can I do this?
I've tried
x.x1.dot(x.x2) however that returns an array [5,11,44], i.e. looks to calculate the dot product in the "wrong" direction.
Thanks!
4 Answers
I think you can using for loop here
x['result']=[np.dot(x,y) for x, y in zip(x.x1,x.x2)] you'd need to access which row to dot: x.x1[0].dot(x.x1[1])= 9
When you access the x.x1, you get a pandas series with two rows.
The response @Wen-Ben response shows you how to get the 'results' column in one line.
The same could be done without using dot().
x['product'] =df.apply(lambda k: sum(k['x1']*(k['x2'])), axis = 1) This would be more easily done by overloading the dot operator on your array, and by "dot" I mean ".".
Thus the correct statement becomes
product = x.x1.x.x2; (Note: be sure to have ellipses turned off in your editor for more complex calculations.)