从 Python 数据框中的时间戳列计算唯一工作日 [英] Count unique weekdays from timestamp column in dataframe in Python

查看:61
本文介绍了从 Python 数据框中的时间戳列计算唯一工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算时间戳中存在多少个唯一的工作日.这是一个输入,我希望输出为 4(因为 8/5 和 8/6 是周末).

I would like to count how many unique weekdays exist in timestamp. Here's an input and I want output to be 4(since 8/5 and 8/6 are weekends).

    captureTime
0   8/1/2017 0:05
1   8/2/2017 0:05
2   8/3/2017 0:05
3   8/4/2017 0:05
4   8/5/2017 0:05
5   8/6/2017 0:05

推荐答案

使用 np.is_busday:

import numpy as np
import pandas as pd
df = pd.DataFrame( {
    'captureTime':[ '8/1/2017 0:05', '8/2/2017 0:05', '8/3/2017 0:05', 
                    '8/4/2017 0:05', '8/5/2017 0:05', '8/6/2017 0:05']})
df['captureTime'] = pd.to_datetime(df['captureTime'])

print(np.is_busday(df['captureTime'].values.astype('datetime64[D]')).sum())

印刷品

4

<小时>

以上,所有工作日都计算一次.如果您只想计算相同的 datetimes 一次,您可以使用

np.is_busday(df['captureTime'].unique().astype('datetime64[D]')).sum()

或者,如果您希望删除具有相同 date 组件的 datetimes,请在调用 之前转换为 datetime64[D] dtype>np.unique:

Or, if you wish to remove datetimes that have identical date components, convert to datetime64[D] dtype before calling np.unique:

np.is_busday(np.unique(df['captureTime'].values.astype('datetime64[D]'))).sum()

这篇关于从 Python 数据框中的时间戳列计算唯一工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆