<p>这是一个<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html" rel="nofollow noreferrer">^{<cd1>}</a>问题。我会这样做:</p>
<pre><code>res = pd.merge_asof(
s0.to_frame(), # should be first, simulate how='left'
i1.to_frame(), # should be second
tolerance=pd.Timedelta(days=2), # two days tolerance
left_on='date', # select index level for s0
right_index=True,
direction='nearest') # default is 'backward', not as useful
s0[res[0].notna()]
date ID
2018-11-30 S 0
O 0
J 0
H 0
D 0
2018-12-30 U 2
S 2
A 2
J 2
L 2
2019-01-17 K 3
U 3
V 3
S 3
H 3
Name: stuff, dtype: int64
</code></pre>
<p>注意,这将保留来自<code>s0</code>的索引(这可能不是您想要的)。你知道吗</p>
<hr/>
<h3>piR编辑</h3>
<p>这就是我想要的</p>
<pre><code>tol = pd.Timedelta(days=2)
right = pd.DataFrame(dict(newdate=i1), i1)
left = s0.to_frame()
kw = dict(
left=left, right=right, tolerance=tol,
left_on='date', right_index=True, direction='nearest'
)
res = pd.merge_asof(**kw)
res = res.dropna() \
.reset_index() \
.set_index(['newdate', 'ID']) \
.stuff.rename_axis(['date', 'ID'])
res
date ID
2018-11-30 S 0
O 0
J 0
H 0
D 0
2018-12-31 U 2
S 2
A 2
J 2
L 2
2019-01-15 K 3
U 3
V 3
S 3
H 3
Name: stuff, dtype: int64
</code></pre>