python - 在小于特定限制的 Pandas DataFrame 的一天中过滤最高可用时间
问题描述
对于这个 Python Pandas DataFrame,我希望一天中时间最长的那一行小于14h00
:
import pandas as pd
import datetime
import numpy as np
df = pd.DataFrame({"a": ["31.12.1997 23:59:12",
"31.12.1998 12:59:12",
"31.12.1999 11:59:13",
"31.12.1999 12:59:13",
"31.12.1999 23:59:14"],
"b": [2,3,4, 5, 6]})
df["date"]=pd.to_datetime(df.a)
df["day"]=df.date.dt.date
所以结果将是:
a b date day
1 31.12.1998 12:59:12 3 1998-12-31 12:59:12 1998-12-31
3 31.12.1999 12:59:13 5 1999-12-31 12:59:13 1999-12-31
由于真正的 DataFrame 很大,因此执行性能很高。
解决方案
利用
In [8]: df.loc[df[df.date.dt.hour.le(14)].groupby('day')['date'].idxmax()]
Out[8]:
a b date day
1 31.12.1998 12:59:12 3 1998-12-31 12:59:12 1998-12-31
3 31.12.1999 12:59:13 5 1999-12-31 12:59:13 1999-12-31
细节
In [9]: df.date.dt.hour.le(14)
Out[9]:
0 False
1 True
2 True
3 True
4 False
Name: date, dtype: bool
In [10]: df[df.date.dt.hour.le(14)]
Out[10]:
a b date day
1 31.12.1998 12:59:12 3 1998-12-31 12:59:12 1998-12-31
2 31.12.1999 11:59:13 4 1999-12-31 11:59:13 1999-12-31
3 31.12.1999 12:59:13 5 1999-12-31 12:59:13 1999-12-31
In [11]: df[df.date.dt.hour.le(14)].groupby('day')['date'].idxmax()
Out[11]:
day
1998-12-31 1
1999-12-31 3
Name: date, dtype: int64
推荐阅读
- c - 为什么这个函数只将第一个收集到的值分配给指针而不是其余的?
- python - 以之字形方式连接字符串列表的算法
- aiml - AIML 给出未找到匹配项
- python-3.x - 用python解压大型机压缩十进制
- c# - 无法使用 iTextSharp 读取 pdf 文件中特定位置的文本
- javascript - 如何在 Node.js 的 readline 中插入换行符?
- android - 如何将 cardview 添加到我的 android studio 项目中?
- laravel - 通过 Laravel 7 中的响应函数发送 Flash 消息
- python - 为什么我使用正确的 xpath 却无法抓取 Indiegogo?
- ruby - 如何判断Ruby对象在哪里定义?