2017-02-28 106 views
0
import pandas as pd 
df1 = pd.DataFrame({'ID':['i1', 'i2', 'i3'], 
        'A': [2, 3, 1], 
        'B': [1, 1, 2], 
        'C': [2, 1, 0], 
        'D': [3, 1, 2]}) 

df1.set_index('ID') 

df1.head() 


    A B C D 
ID   
i1 2 1 2 3 
i2 3 1 1 1 
i3 1 2 0 2 


df2 = pd.DataFrame({'ID':['i1-i2', 'i1-i3', 'i2-i3'], 
        'A': [2, 1, 1], 
        'B': [1, 1, 1], 
        'C': [1, 0, 0], 
        'D': [1, 1, 1]}) 

df2.set_index('ID') 
df2 

     A B C D 
ID    
i1-i2 2 1 1 1 
i1-i3 1 1 0 1 
i2-i3 1 1 0 1 

給定一個數據幀爲df1,像df2這樣的新數據幀。 例如,比較i1行和i2行,獲得新的行i1-i22, 1, 1, 1 請指教一下是大熊貓做到這一點的最好辦法。熊貓:比較每兩行並輸出結果到一個新的數據幀

回答

1

試試這個:

from itertools import combinations 

v = df1.values 

r = pd.DataFrame([np.minimum(v[t[0]], v[t[1]]) 
        for t in combinations(np.arange(len(df1)), 2)], 
       columns=df1.columns, 
       index=list(combinations(df1.index, 2))) 

結果:

In [72]: r 
Out[72]: 
      A B C D 
(i1, i2) 2 1 1 1 
(i1, i3) 1 1 0 2 
(i2, i3) 1 1 0 1 
+0

它是美麗的方式,使組合。但新的數據幀丟失了ID組合。你能提出一種方法來保持這一點嗎? –

+0

@ju。,我已經更新了我的答案 - 請檢查 – MaxU