【问题标题】:Python Pandas Find all weekends/dates between two date columnsPython Pandas 查找两个日期列之间的所有周末/日期
【发布时间】:2019-08-24 03:49:47
【问题描述】:

假设我有一个包含两列的数据框

Start      End
1/1/2015  1/5/2015
1/10/2015 1/12/2015

获取开始和结束日期之间的日期(实际日期,而不是中间的天数)的最佳方法是什么,包括开始日期和结束日期。

例如,我会得到 2015 年 1 月 1 日、2015 年 1 月 2 日、...、2015 年 1 月 5 日。

我想这样做的原因是要找出两个日期之间有多少个周末。

这是示例数据框以及快速解析日期的代码。

def lookup(s):
    """
    This is an extremely fast approach to datetime parsing.
    For large data, the same dates are often repeated. Rather than
    re-parse these, we store all unique dates, parse them, and
    use a lookup to convert all dates.
    """
    dates = {date:pd.to_datetime(date) for date in s.unique()}
    return s.map(dates)

df = pd.DataFrame({"Start": ["1/1/2015", "1/10/2015"], "End": ["1/5/2015", "1/12/2015"]})
df["Start"] = lookup(df["Start"])
df["End"] = lookup(df["End"])

如果有人知道更好的方法,请告诉我,因为我认为有更好的方法来查找两个日期之间的周末数。

我试图理解 pd.date_range() 函数并尝试像这样应用它。

df["between"] = pd.date_range(df["Start"], df["End"])

但是得到一个错误说它不能转换输入,我知道我错误地使用了这个函数。我想我需要使用 apply 但不确定如何将它与此功能一起使用。

感谢任何帮助。如果您需要更多信息,请告诉我。

感谢您的宝贵时间。

【问题讨论】:

标签: python pandas date datetime


【解决方案1】:

您可以利用pandas 使用的内置dataoffsetsbdate_range() 在这里成为你的朋友

# create a dataframe of dates
df = pd.DataFrame({'Dates': pd.date_range("2015-01-01", "2019-08-01")})

# create a series of business days
busines_dates = pd.bdate_range("2015-01-01", "2019-08-30")

# find where the two do not intersect
df.loc[~df['Dates'].isin(busines_dates)]

根据您的问题,我觉得您可能希望将此作为功能。这是一个基本的:

def weekends(start, end):
    df = pd.DataFrame({'Dates': pd.date_range(start, end)})
    busines_dates = pd.bdate_range(start, end)
    answer = df.loc[~df['Dates'].isin(busines_dates)]
    print("There are", answer.shape[0], 'weekends between', start, 'and', end)
    return answer

weekends("2015-01-01", "2019-01-01")


There are 418 weekends between 2015-01-01 and 2019-01-01
          Dates
2    2015-01-03
3    2015-01-04
9    2015-01-10
10   2015-01-11
16   2015-01-17
...         ...
1445 2018-12-16
1451 2018-12-22
1452 2018-12-23
1458 2018-12-29
1459 2018-12-30

【讨论】:

  • 哇,这太棒了!谢谢,这超出了我的预期,这个功能将非常有用!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2011-04-17
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多