<p>不是100%清楚你真正想要什么(例如什么是“num<;10”,哪个num?Id1\u num还是id2\u num?)但我相信下面的内容会让你更接近。你知道吗</p>
<p>第一组df2并将其格式化为日期间隔:</p>
<pre><code>df2_grouped = df2.groupby(['ID1', 'ID2']).\
apply(lambda x: pd.Series([x['Date'].min(), x['Date'].max(),
x['id2_num'].count()],
index=['StartDate2', 'EndDate2', 'ID1Date1Count']))
df2_grouped = df2_grouped.reset_index()
print(df2_grouped)
ID1 ID2 StartDate2 EndDate2 ID1Date1Count
0 111 10 1/1/2017 4/1/2017 3
1 112 20 2/1/2017 4/1/2017 1
2 113 20 1/1/2017 2/1/2017 2
3 114 30 2/1/2017 4/1/2017 2
4 115 30 4/1/2017 5/1/2017 2
</code></pre>
<p>然后将其与df1合并:</p>
<pre><code>df1[['ID1', 'StartDate1', 'EndDate1']].merge(df2_grouped, on='ID1')
df1 = df1.sort_values(by=['StartDate2'])
print(df1)
ID1 StartDate1 EndDate1 ID2 StartDate2 EndDate2 ID1Date1Count
0 111 1/1/2017 3/1/2017 10 1/1/2017 4/1/2017 3
2 113 1/1/2017 2/1/2017 20 1/1/2017 2/1/2017 2
1 112 2/1/2017 3/1/2017 20 2/1/2017 4/1/2017 1
3 114 2/1/2017 4/1/2017 30 2/1/2017 4/1/2017 2
4 115 4/1/2017 5/1/2017 30 4/1/2017 5/1/2017 2
</code></pre>
<p>同样,输出与所需的输出并不完全匹配,但非常接近。你知道吗</p>