2016-06-10 64 views
2

我有一个数据帧df1如何在不使用for-loop的情况下基于来自另一个Dataframe的值来分割pandas DataFrame?

df1.head() =  
      id type position 
dates 
2000-01-03 17378 600  400 
2000-01-03 4203 600  150 
2000-01-03 18321 600  5000 
2000-01-03 6158 600  1000 
2000-01-03 886 600  10000 
2000-01-03 17127 600  800 
2000-01-03 18317 1300  110 
2000-01-03 5536 600  207 
2000-01-03 5132 600  20000 
2000-01-03 18191 600  2000  

和第二数据帧df2

df2.head() = 

       dt_f  dt_l 
id_y id_x 
670 715 2000-02-14 2003-09-30 
704 2963 2000-02-11 2004-01-13 
886 18350 2000-02-09 2001-09-24 
1451 18159 2005-11-14 2007-03-06 
2175 8648 2007-02-28 2007-09-19 
2236 18321 2001-04-05 2002-07-02 
2283 2352 2007-03-07 2007-09-19 
     6694 2007-03-07 2007-09-17 
     13865 2007-04-19 2007-09-19 
     14348 2007-08-10 2007-09-19 
     15415 2007-03-07 2007-09-19 
2300 2963 2001-05-30 2007-09-26 

我需要切片df1用于id_x每个值,间隔dt_f:dt_l内计数的行数。对于id_y的值,这必须再次完成。最后的结果必须在df2被合并,得到作为输出以下数据帧:

df_result.head() = 

       dt_f  dt_l  n_x n_y 
id_y id_x 
670 715 2000-02-14 2003-09-30 8  10 
704 2963 2000-02-11 2004-01-13 13 25 
886 18350 2000-02-09 2001-09-24 32 75 
1451 18159 2005-11-14 2007-03-06 48 6 

n_x哪里(n_y)对应于包含在用于id_x(id_y各值)的间隔dt_f:dt_l的行数。

下面是for循环我用:

idx_list = df2.index.tolist() 
k = 1 
for j in idx_list: 
    n_y = df1[df1.id == j[0]][df2['dt_f'].iloc[k]:df2['dt_l'].iloc[k]]['id'].count() 
    n_x = df1[df1.id == j[1]][df2['dt_f'].iloc[k]:df2['dt_l'].iloc[k]]['id'].count() 

有没有可能做到这一点,而无需使用一个for循环? DataFrame df1包含大约30000行,恐怕一个循环会减慢过程的速度,因为这是整个脚本的一小部分。

+0

为什么'n_y'与'n_x'不同?你能告诉我们你的“for”循环吗? – IanS

+0

你满意目前的答案吗?作为一个附注,你应该检查如何发布[MCVE]。理想情况下,你的输入将导致你想要的输出,这将使人们更容易检查他们的答案(并且理解问题)。 – IanS

+0

感谢IanS发表您的评论 –

回答

0

你想是这样的:

#Merge the tables together - making sure we keep the index column 
mg = df1.reset_index().merge(df2, left_on = 'id', right_on = 'id_x') 

#Select only the rows that are within the start and end 
mg = mg[(mg['index'] > mg['dt_f']) & (mg['index'] < mg['dt_l'])] 

#Finally count by id_x 
mg.groupby('id_x').count() 

你需要事后收拾列并重复id_y。

+0

非常感谢!它完美的工作! (我使用mg ['dates']而不是mg ['index']来重新设置df和and的索引,从而将其调整为我的代码) –

相关问题