2
votes

I have nine lists (columns of a dataframe to be precise), and I would like to do matrix operations with all rows of these columns. For example, I need to do this operation:

O(G) = trace(G*transpose(G)) + trace(G*G), where G is a 3x3 matrix defined by each rows of the columns. For example, for two rows:

a,b,c,d,e,f,g,h,i
1,2,3,4,5,6,7,8,9
5,6,9,8,7,4,5,2,3

The two matrices should be:

G1 = [1,2,3; 4,5,6; 7,8,9] > perform O(G1) = 546

G2 = [5,6,9; 8,7,4; 5,2,3] > perform O(G2) = 594

and then, put them into a new column:

a,b,c,d,e,f,g,h,i,O
1,2,3,4,5,6,7,8,9,546
5,6,9,8,7,4,5,2,3,594

How can I proceed with this? I think numpy doesn't permit create matrices with list as values...

3

3 Answers

3
votes

We can do row by row

l=[]
for x  in df.index:

     n=df.loc[x].values.reshape(3,3) 
     l.append(np.trace(n.dot(n))+np.trace(n.dot(n.T)))

l
[546, 594]
df['new']=l
2
votes

Use numpy reshape() and flatten():

import numpy as np

list_a = [1,2,3,4,5,6,7,8,9]

matrix_a = np.reshape(list_a, (3, 3))

>>> array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
1
votes

you can use two einsum on the data from df reshape:

G = df.to_numpy().reshape(-1,3,3)
array([[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]],

       [[5, 6, 9],
        [8, 7, 4],
        [5, 2, 3]]], dtype=int64)

df['0'] = np.einsum('ijk,ikj->i', G, G) + np.einsum('ijk,ijk->i', G, G)
   a  b  c  d  e  f  g  h  i    0
0  1  2  3  4  5  6  7  8  9  546
1  5  6  9  8  7  4  5  2  3  594