首页 > 解决方案 > 在小于特定限制的 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 很大,因此执行性能很高。

标签: pythonpandasdataframe

解决方案


利用

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

推荐阅读