<p>我创建了一些示例数据,以更好地说明我相信您正在尝试做的事情</p>
<p>然后,您可以使用<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmax.html" rel="nofollow noreferrer">^{<cd1>}</a>通过以下方式获得每个月最大值的索引位置<code>data</code>:</p>
<p><code> df.groupby(pd.Grouper(key='Date', freq='M'))['data'].idxmax()</code></p>
<p>然后使用<code>loc</code>在这些每月最大值上对数据帧进行子集(如果您愿意,还可以附加<code>.set_index('Date')</code>作为索引)</p>
<pre><code>np.random.seed(0)
timestamps = pd.DatetimeIndex(start='2020-01-01', end='2020-10-01', freq='1h')
data = np.random.randn(len(timestamps))
df = pd.DataFrame({'Date': timestamps, 'data': data})
monthly_max_vals = df.groupby(
pd.Grouper(key='Date', freq='M'))['data'].idxmax()
>>> df.loc[monthly_max_vals].reset_index(drop=True)
Date data
0 2020-01-21 14:00:00 2.696224
1 2020-02-13 22:00:00 3.170975
2 2020-03-26 20:00:00 2.929096
3 2020-04-05 14:00:00 2.464322
4 2020-05-09 22:00:00 3.801660
5 2020-06-08 10:00:00 2.600672
6 2020-07-23 13:00:00 2.979976
7 2020-08-23 16:00:00 2.841767
8 2020-09-30 17:00:00 2.944984
9 2020-10-01 00:00:00 0.817049
</code></pre>