python - 具有日期比较条件的非纳米值的 Pandas 数据框中的计数值

标签 python pandas dataframe

我有以下数据框:

Date_1                  Date_2                  Date_3
2019-12-18 13:43:47                             2019-12-18 13:43:47
2019-12-18 13:43:48     2019-12-18 13:43:47     
2020-12-18 17:51:17
2020-12-18 17:51:17     2020-12-18 17:51:17     2020-12-18 17:51:17

我正在尝试计算每列中存在的值的数量(如果它们满足日期超过今天的条件)。

我的代码:

today=pd.Timestamp.today() - pd.Timedelta(days=1)

total_date_1_events = len([df['Date_1']>today])+1
total_date_2_events = len([df['Date_2']>today])+1
total_date_3_events = len([df['Date_3']>today])+1

如果我打印 3 个变量中的每一个,它们都会输出相同的结果,即 4,我知道这是因为空行也被计​​算在内。

我希望得到以下结果:

total_date_1_events = 2 # because there are only 2 dates that are bigger than today
total_date_2_events = 1 # because there are only 1 date that is bigger than today
total_date_3_events = 1 # because there are only 1 date that is bigger than today

感谢您的建议。

最佳答案

简单地做:

sum(df.Date_1>pd.Timestamp.today())
sum(df.Date_1>pd.Timestamp.today())
sum(df.Date_1>pd.Timestamp.today())

关于python - 具有日期比较条件的非纳米值的 Pandas 数据框中的计数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60323683/

相关文章:

python - 有效地找到最相似的集合(Python,数据结构)

python - 如何在用户单击框架的关闭时终止 WxPython 应用程序

python - 检测 Python 循环中的值变化

python - Pandas DataFrame - 列出具有最低不同值的列

python - 用列表填充 Pandas 列的空值

python - 如果所有列都为空字符串,则从 pandas 数据框中删除行

python - 用python解析xml中的CDATA

python - Pandas:删除具有 nan 值索引的行

python - Pandas 如何使用 dt 按月和年分组

python - 如何将数据从np矩阵加载到seaborn?