2014-09-06 49 views
0

我有兩個數據幀:Python的大熊貓查找/交叉引用

In [6]: df1 = pd.DataFrame({'word':['laugh','smile','frown','cry'],'score':[7,2,-3,-8]}, columns=['word','score']) 
     df1 

Out[6]:  word score 
     0 laugh 7 
     1 smile 2 
     2 frown -3 
     3 cry -8 

In [8]: df2 = pd.DataFrame({'word':['frown','laugh','play']}) 
     df2 

Out[8]: 
      word 
     0 frown 
     1 laugh 
     2 play 

我知道我可以它們合併起來,並得到每個單詞的得分:

In [10]: pd.merge(df1,df2) 

Out[10]: word score 
     0 laugh 7 
     1 frown -3 

不過,我可以」 t相當包攬我的頭圍繞如何:

i)自動將0分數分配給沒有分數的單詞。所以,「play」是在df2中,但在合併之後被刪除,但是我想在合併之後保留它。我期望df2包含許多沒有分數的單詞,因此不可能簡單地將這些單詞添加到df1並將它們分配爲零。所以,我想合併,以此來代替:

Out[10]: word score 
     0 laugh 7 
     1 frown -3 
     2 play 0 

ii)我怎樣才能得到多個單詞的平均分數。所以,如果我的數據幀看起來像這個:

In [14]: df3 = pd.DataFrame({'words':['frown cry','laugh smile','play laugh', 'cry laugh play smile']}) 
     df3 

Out[14]: words 
     0 frown cry 
     1 laugh smile 
     2 play laugh 
     3 cry laugh play smile 

我希望能夠交叉參考DF3與DF1獲得:

Out[14]: words     average_score 
     0 frown cry    -5.5 
     1 laugh smile   4.5 
     2 play laugh    3.5 
     3 cry laugh play smile 0.25 

希望我做數學吧!我猜測熊貓可能有另一種/更好的方法來做到這一點?

回答

1

對於(i)您只需要指定right加入,並填寫空值:

>>> pd.merge(df1, df2, how='right').fillna(0) 
    word score 
0 laugh  7 
1 frown  -3 
2 play  0 

爲(ii)您可以這樣做:

>>> def grpavg(ws): 
...  i = df1['word'].isin(ws) 
...  return df1.loc[i, 'score'].sum()/len(ws) 
... 
>>> df3['avg-score'] = df3['words'].str.split().map(grpavg) 
>>> df3 
        words avg-score 
0    frown cry  -5.50 
1   laugh smile  4.50 
2   play laugh  3.50 
3 cry laugh play smile  0.25 

編輯:回答的評論,明確傳遞幀,然後使用lambdafunctools.partial進行綁定:

>>> def grpavg(ws, df): 
...  i = df['word'].isin(ws) 
...  return df.loc[i, 'score'].sum()/len(ws) 
... 
>>> from functools import partial 
>>> f = partial(grpavg, df=df1) 
>>> df3['avg-score'] = df3['words'].str.split().map(f) 
>>> df3 
        words avg-score 
0    frown cry  -5.50 
1   laugh smile  4.50 
2   play laugh  3.50 
3 cry laugh play smile  0.25 
+0

i f grpavg被放置在一個模塊中,那麼我需要做些什麼來確保df1可以被此函數訪問(假設df1正在從文件中讀取)?我應該有一個函數可以從文件中讀取列表,然後將grpavg更改爲兩個參數作爲輸入(ws和一個可選的數據框,這可以交叉引用)? – slaw 2014-09-06 18:52:47

+0

@slaw是的,正確的方法是明確地傳遞框架。看編輯 – 2014-09-06 19:09:59