<p>首先将<code>B</code>设置为索引,以便对其使用<code>Groupby.resample</code>方法。在</p>
<pre><code>df.set_index('B', inplace=True)
</code></pre>
<p>Groupby<code>A</code>并根据秒频率重新采样。由于重采样不能直接用于滚动,请使用<code>ffill</code>(向前<code>fillna</code>,其中<code>NaN</code>限制为0)。
现在使用<code>rolling</code>函数,方法是将窗口大小指定为4(因为<code>freq=4s</code>)间隔,并在<code>C</code>列取平均值,如下所示:</p>
^{pr2}$
<p>获得的结果输出:</p>
<pre><code>B
2016-01-01 09:30:00 NaN
2016-01-01 09:30:01 NaN
2016-01-01 09:30:02 NaN
2016-01-01 09:30:03 1.5
2016-01-01 09:30:04 2.5
2016-01-01 09:30:05 3.5
2016-01-01 09:30:06 4.5
2016-01-01 09:30:07 5.5
2016-01-01 09:30:08 6.5
2016-01-01 09:30:09 7.5
Freq: S, Name: C, dtype: float64
B
2016-01-01 09:30:00 NaN
2016-01-01 09:30:01 NaN
2016-01-01 09:30:02 NaN
2016-01-01 09:30:03 21.5
2016-01-01 09:30:04 22.5
2016-01-01 09:30:05 23.5
2016-01-01 09:30:06 24.5
2016-01-01 09:30:07 25.5
2016-01-01 09:30:08 26.5
2016-01-01 09:30:09 27.5
Freq: S, Name: C, dtype: float64
B
2016-01-01 09:30:12 NaN
2016-01-01 09:30:13 NaN
2016-01-01 09:30:14 NaN
2016-01-01 09:30:15 33.5
2016-01-01 09:30:16 34.5
2016-01-01 09:30:17 35.5
2016-01-01 09:30:18 36.5
2016-01-01 09:30:19 37.5
Freq: S, Name: C, dtype: float64
</code></pre>
<hr/>
<p><strong><em>TL;DR</em></strong></p>
<p>请在适当设置索引后使用<a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow noreferrer">^{<cd10>}</a>作为解决方法:</p>
<pre><code># tested in version - 0.19.1
df.groupby('A').apply(lambda grp: grp.resample('s').ffill(limit=0).rolling(4)['C'].mean())
</code></pre>
<p>(或)</p>
<pre><code># Tested in OP's version - 0.19.0
df.groupby('A').apply(lambda grp: grp.resample('s').ffill().rolling(4)['C'].mean())
</code></pre>
<p>两者都有用。在</p>