2016-05-20 101 views
0

我有一個數據幀。我想把每一列的內在產品與自己相提並論。矩陣的內積

到目前爲止,我已經做到了這一點:

import pandas as pd 
import numpy as np 

np.random.seed([3, 1415]) 
df = pd.DataFrame(np.random.rand(10, 3).round(2), columns=['one', 'two', 'three']) 

inner_df = df.T.dot(df) 
print inner_df 
print 

tot = 0 
for i in range(len(inner_df)): 
    tot += inner_df.iloc[i, i] 

print "total =", tot 

      one  two three 
one 3.7611 3.4669 3.4766 
two 3.4669 3.6323 3.1140 
three 3.4766 3.1140 3.5214 

total = 10.9148 

這讓我我需要什麼,但感覺很笨拙。什麼是更乾淨的方式呢?

+0

最好去問有關的代碼審查:http://codereview.stackexchange.com/ – Idos

+0

如果代碼按預期工作(這似乎是這種情況),這將是對代碼審查確定。 – Phrancis

回答

1

矢量化解決方案如下所示。

import pandas as pd 
import numpy as np 

np.random.seed([3, 1415]) 
df = pd.DataFrame(np.random.rand(10, 3).round(2), columns=['one', 'two', 'three']) 

# pandas approach 
print df.mul(df).sum().sum() 

# numpy approach 
print np.square(df.values).sum() 

10.9148 
10.9148