2014-02-16 174 views
0

我是熊猫新手,试图转换我的一些SAS代码。我有两个数据集,第一个(header_mf)包含由crsp_fundno和caldt(基金ID和日期)索引的共同基金信息。在第二个数据(ret_mf)中,我有相同指数的资金回报(mret列)。我试图将第一个数据集中的每个条目与前12个月的回报合并。在SAS,我可以做这样的事情:条件合并熊猫

proc sql; 
    create table temp_mf3 as 
    select a.*, b.mret from header_mf as a, 
    ret_mf as b where 
    a.crsp_fundno=b.crsp_fundno and 
    ((year(a.caldt)=year(b.caldt) and month(a.caldt)>month(b.caldt)) or 
    (year(a.caldt)=(year(b.caldt)+1) and month(a.caldt)<=month(b.caldt))); 
    quit; 

在Python中,我试着crsp_fundno连接两个数据帧而已,希望能在接下来的步骤中排除了超范围的意见。但是,结果很快变得太大而无法处理,而且内存不足(我正在使用超过15年的数据)。

有没有一种有效的方式来做这种熊猫条件下的条件合并?

回答

1

对不起,如果这个答复来得晚,以帮助。我不认为你想要一个条件合并(至少如果我正确地理解情况)。我认为只需合并['fundno','caldt']上的header_mf和ret_mf,然后使用熊猫中的shift运算符创建过去的回报列,就可以得到您想要的结果。

因此,我认为你的数据基本如下所示:

import pandas as pd 
header = pd.read_csv('header.csv') 
print header 

    fundno  caldt foo 
0  1 1986-06-30 100 
1  1 1986-07-31 110 
2  1 1986-08-29 120 
3  1 1986-09-30 115 
4  1 1986-10-31 110 
5  1 1986-11-28 125 
6  1 1986-12-31 137 
7  2 1986-06-30 130 
8  2 1986-07-31 204 
9  2 1986-08-29 192 
10  2 1986-09-30 180 
11  2 1986-10-31 200 
12  2 1986-11-28 205 
13  2 1986-12-31 205 

ret_mf = pd.read_csv('ret_mf.csv') 
print ret_mf 

    fundno  caldt mret 
0  1 1986-06-30 0.05 
1  1 1986-07-31 0.01 
2  1 1986-08-29 -0.01 
3  1 1986-09-30 0.10 
4  1 1986-10-31 0.04 
5  1 1986-11-28 -0.02 
6  1 1986-12-31 -0.06 
7  2 1986-06-30 -0.04 
8  2 1986-07-31 0.03 
9  2 1986-08-29 0.07 
10  2 1986-09-30 0.00 
11  2 1986-10-31 -0.05 
12  2 1986-11-28 0.09 
13  2 1986-12-31 0.04 

很明显,头文件中可能存在很多的变数(除了我由foo变量)。但是,如果这基本上捕获数据的性质那么我认为你可以合并在['fundno','caldt']然后用shift

mf = header.merge(ret_mf,how='left',on=['fundno','caldt']) 
print mf 

    fundno  caldt foo mret 
0  1 1986-06-30 100 0.05 
1  1 1986-07-31 110 0.01 
2  1 1986-08-29 120 -0.01 
3  1 1986-09-30 115 0.10 
4  1 1986-10-31 110 0.04 
5  1 1986-11-28 125 -0.02 
6  1 1986-12-31 137 -0.06 
7  2 1986-06-30 130 -0.04 
8  2 1986-07-31 204 0.03 
9  2 1986-08-29 192 0.07 
10  2 1986-09-30 180 0.00 
11  2 1986-10-31 200 -0.05 
12  2 1986-11-28 205 0.09 
13  2 1986-12-31 205 0.04 

现在可以创建过去回归变量。因为我创建了这样一个小例子面板,我只会做3个月的过去回报:

for lag in range(1,4): 
    good = mf['fundno'] == mf['fundno'].shift(lag) 
    mf['ret' + str(lag)] = mf['mret'].shift(lag).where(good) 
print mf 

    fundno  caldt foo mret ret1 ret2 ret3 
0  1 1986-06-30 100 0.05 NaN NaN NaN 
1  1 1986-07-31 110 0.01 0.05 NaN NaN 
2  1 1986-08-29 120 -0.01 0.01 0.05 NaN 
3  1 1986-09-30 115 0.10 -0.01 0.01 0.05 
4  1 1986-10-31 110 0.04 0.10 -0.01 0.01 
5  1 1986-11-28 125 -0.02 0.04 0.10 -0.01 
6  1 1986-12-31 137 -0.06 -0.02 0.04 0.10 
7  2 1986-06-30 130 -0.04 NaN NaN NaN 
8  2 1986-07-31 204 0.03 -0.04 NaN NaN 
9  2 1986-08-29 192 0.07 0.03 -0.04 NaN 
10  2 1986-09-30 180 0.00 0.07 0.03 -0.04 
11  2 1986-10-31 200 -0.05 0.00 0.07 0.03 
12  2 1986-11-28 205 0.09 -0.05 0.00 0.07 
13  2 1986-12-31 205 0.04 0.09 -0.05 0.00 

我很抱歉,如果我误解了您的数据。