Skip to main content
 首页 » 编程设计

python之重新采样时间序列并显示一天中的时间

2024年09月07日12zhujiabin

这让我发疯。我试图在显示时间序列发生时的一天中的时间的同时找到时间序列的最大每日值。我有一个日期时间索引、第二个日期时间列和一个最高温度。如果我这样做

temperature_max = temperature.resample('D').max() 

我得到了时间 (23:59) 和温度的最大值。如何获得最高温度发生的时间?非常感谢!

请您参考如下方法:

我相信您需要 idxmax 作为最大 temperature 的索引,然后通过 loc 选择:

temperature_max = temperature.loc[temperature.resample('D')['temperature'].idxmax()] 

示例:

rng = pd.date_range('2017-04-03', periods=10) 
r = pd.date_range('2017-04-03', periods=10, freq='12H') 
temperature = pd.DataFrame({'Date': rng, 'temperature': range(10)}, index=r)   
print (temperature) 
                          Date  temperature 
2017-04-03 00:00:00 2017-04-03            0 
2017-04-03 12:00:00 2017-04-04            1 
2017-04-04 00:00:00 2017-04-05            2 
2017-04-04 12:00:00 2017-04-06            3 
2017-04-05 00:00:00 2017-04-07            4 
2017-04-05 12:00:00 2017-04-08            5 
2017-04-06 00:00:00 2017-04-09            6 
2017-04-06 12:00:00 2017-04-10            7 
2017-04-07 00:00:00 2017-04-11            8 
2017-04-07 12:00:00 2017-04-12            9 
 
temperature_max = temperature.loc[temperature.resample('D')['temperature'].idxmax()] 
print (temperature_max) 
                          Date  temperature 
2017-04-03 12:00:00 2017-04-04            1 
2017-04-04 12:00:00 2017-04-06            3 
2017-04-05 12:00:00 2017-04-08            5 
2017-04-06 12:00:00 2017-04-10            7 
2017-04-07 12:00:00 2017-04-12            9