熊猫发现DateTimeIndex

时间:2018-10-07 00:40:00

标签: python pandas

我正在尝试计算两个熊猫DateTimeIndex数据集之间的差异。

start_date = "2012-01-01"
end_date = "2012-12-31"

workdays = pd.bdate_range(start_date,end_date)
all_days = pd.date_range(start_date,end_date)

我尝试过:

#Method A
weekends = np.subtract(all_days, workdays)
#ValueError: operands could not be broadcast together with shapes (366,) (262,) 

#Method B
weekends = pd.DatetimeIndex
for d in all_days:
    if d not in workdays:
        weekends.append(d)
#TypeError: append() missing 1 required positional argument: 'other'

#Method C
weekends = all_days - workdays.reindex(all_days.index, fill_value=0)
#AttributeError: 'DatetimeIndex' object has no attribute 'index'

#Method D
weekends = all_days - workdays
#ValueError: cannot add indices of unequal length

熊猫版本== 0.23.4

任何想法我该怎么做

2 个答案:

答案 0 :(得分:1)

我会做这样的事情来度过周末:

import numpy as np

weekends = all_days[np.logical_not(all_days.isin(workdays))]

答案 1 :(得分:1)

如果您的目标是获取所有周末的约会,那么这将更加有效和直接:

satsun = pd.offsets.CustomBusinessDay(weekmask='Sat Sun')
offdays = pd.bdate_range(start_date, end_date, weekmask=satsun)

https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.busdaycalendar.html上查看weekmask上的文档