python - 返回最大日期时间值
问题描述
这是我的代码
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
有人可以在这方面帮助我吗
解决方案
您可以使用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]
,那么您可以等效地使用更高效的.iat
or.iloc
访问器。
pd.Series.argmax
返回第一次出现最大值的索引。pd.DataFrame.loc
允许按索引标签进行索引,因此将两者联系起来我们可以达到预期的结果。
推荐阅读
- php - PHP 使用 PublicKey 和 CredentialId 对用户进行身份验证
- java - 如何将字符串 json 映射到 POJO 类?
- java - 如何在spring boot中使用弹性搜索模板id(存储在ES集群中)获取结果
- php - 获取 x 值为 2.9
- mysql - MySQL正向工程:表不是在工作台的方案中创建,而是在“mydb”(模型)中创建
- ios - 构建时 Xcode 12.5.1 出错,(错误 spawnSync xcodebuild ENOBUFS)
- android - android模拟器中的条码扫描测试
- html - 如何在表格中的表格标题上放置边框半径?
- flutter - 使用颤振在pdf中添加图形
- android - 如果没有验证证明、会话信息、临时证明或注册 ID,则无法创建 PhoneAuthCredential,其他不符合 sol 的解决方案