2014-11-23 155 views
1

我有一個DataFrame x有三列;用兩個條件和多個值對數據幀求和

a b c  
1 1 10 4 
2 5 6 5 
3 4 6 5 
4 2 11 9   
5 1 2 10  

...和兩個值的系列y;

t 
1 3 
2 7 

現在我想要一個DataFrame z有兩列;

t sum_c  
1 3 18 
2 7 13 

...其中t來自y和sum_c對於t大於a且小於b的所有行,c來自x的總和。

有人能幫助我嗎?

回答

0

這裏是基於給定的條件(在烏拉圭回合問題列出不相當給定條件排隊的預期結果)一個可能的解決方案:

In[99]: df1 

Out[99]: 
    a b c 
0 1 10 4 
1 5 6 5 
2 4 6 5 
3 2 11 9 
4 1 2 10 

In[100]: df2 

Out[100]: 
    t 
0 3 
1 5 

然後寫這將由熊貓使用的功能。適用於()後:

In[101]: def cond_sum(x): 
    return sum(df1['c'].ix[np.logical_and(df1['a']<x.ix[0],df1['b']>x.ix[0])]) 

最後:

In[102]: df3 = df2.apply(cond_sum,axis=1) 

In[103]: df3 
Out[103]: 
0 13 
1 18 
dtype: int64 
+0

這是偉大的,非常非常感謝! – mrhosman 2014-11-23 15:16:47

+0

對你的出色答案進行小小的調整:import pandas as pd import numpy as np df1 = pd.DataFrame({'a':pd.Series([1,5,4,2,1]),'b': pd.Series([10,6,6,11,2]),'c':pd.Series([4,5,5,9,10])}) df2 = pd.DataFrame({'t' :pd.Series([3,5])) def cond_sum(x):return sum(df1 ['c']。ix [np.logical_and(df1 ['a'] x.ix [0])]) pd.concat([df2,pd.DataFrame({'sum_c':df2.apply(cond_sum,axis = 1)})],axis = 1 ) – mrhosman 2014-11-23 15:30:49

+0

啊你的權利。有一個錯字。只是做了改變 – leo 2014-11-24 01:52:56