2017-03-07 77 views
2

我有兩隻大熊貓作爲Datafrmae映射在大熊貓有多個按鍵

df:       df2: 
    col1 col2 val    col1 col2 s 
0  1 a 1.2   0  1 a 0.90 
1  2 b 3.2   1  3 b 0.70 
2  2 a 4.2   2  1 b 0.02 
3  1 b -1.2   3  2 a 0.10 

,我想用df2['s']和繁殖它df['val']每當['col1', 'col2']匹配的組合。如果某行不匹配,我並不需要做乘法

我創建一個映射

mapper = df2.set_index(['col1','col2'])['s'] 

從哪裏獲得

mapper 
col1 col2 
1  a  0.90 
3  b  0.70 
1  b  0.02 
2  a  0.10 
Name: s, dtype: float64 

,我想與df[['col1','col2']]

與之匹敵
df[['col1','col2']] 

    col1 col2 
0  1 a 
1  2 b 
2  2 a 
3  1 b 

但是當我做映射時

mapped_value = df[['col1','col2']].map(mapper) 

我收到以下錯誤

AttributeError: 'DataFrame' object has no attribute 'map'

任何暗示?

回答

1

我想你需要mul

df = df2.set_index(['col1','col2'])['s'].mul(df.set_index(['col1','col2'])['val']) 
print (df) 

col1 col2 
1  a  1.080 
     b  -0.024 
2  a  0.420 
     b   NaN 
3  b   NaN 
dtype: float64 

如果需要更換NaN

df = df2.set_index(['col1','col2'])['s'] 
     .mul(df.set_index(['col1','col2'])['val'], fill_value=1) 
print (df) 
col1 col2 
1  a  1.080 
     b  -0.024 
2  a  0.420 
     b  3.200 
3  b  0.700 
dtype: float64 
+0

感謝。它做我需要的! – Hamed