首页 > 解决方案 > 返回最大日期时间值

问题描述

这是我的代码

file = pd.read_excel(open("file name",'rb'),sheetname="data")
max_vol = file["Voltage"].max()
max_time = file.loc["Voltage"]==max_vol,"Timestamp"]

我的时间戳有这样的数据

0      2018-03-01 00:00:00
1      2018-03-01 00:05:00
2      2018-03-01 00:10:00
3      2018-03-01 00:15:00
4      2018-03-01 00:20:00
5      2018-03-01 00:25:00
6      2018-03-01 00:30:00
7      2018-03-01 00:35:00
8      2018-03-01 00:40:00
9      2018-03-01 00:45:00
10     2018-03-01 00:50:00
11     2018-03-01 00:55:00
12     2018-03-01 01:00:00
13     2018-03-01 01:05:00
14     2018-03-01 01:10:00
15     2018-03-01 01:15:00
16     2018-03-01 01:20:00

打印 max_time 时,我得到的结果如下

624   2018-03-03 04:00:00

Name: Timestamp, dtype: datetime64[ns]

但我只想

2018-03-03 04:00:00

有人可以在这方面帮助我吗

标签: pythondatetimeseries

解决方案


您可以使用argmax提取最大元素的索引,然后使用pd.DataFrame.loc

df['datetime'] = pd.to_datetime(df['datetime'])  # convert to datetime
res = df['datetime'].loc[df['voltage'].argmax()]

如果您知道您的索引是从 0 开始的整数范围,例如[0, 1, 2],那么您可以等效地使用更高效的.iator.iloc访问器。

pd.Series.argmax返回第一次出现最大值的索引。pd.DataFrame.loc允许按索引标签进行索引,因此将两者联系起来我们可以达到预期的结果。


推荐阅读