【问题标题】:check-in date with check-out date入住日期和退房日期
【发布时间】:2020-12-17 18:53:02
【问题描述】:

我在 jupyter notebook 上学习,我创建了一个我无法解决的问题 我有一个带有两列日期的数据框(已经是数据时间格式) column1 是输入日期 column2 是出发日期

如何创建一个日期范围在 column1 和 column2 之间的新列? 在python中

【问题讨论】:

  • 当你说数据范围时,你是指column1和column2中日期之间的天数吗?还是您想要这两个日期之间的日期列表?
  • 你能分享一个示例 DataFrame 和预期的输出吗?
  • df A B 一 2014-01-01 2014-02-28 二 2014-02-03 2014-03-01

标签: python pandas datetime jupyter-notebook


【解决方案1】:

由于缺少示例 DataFrame,我将一个随机日期生成器拼凑在一起。其他人,请随意使用它来创建比我更清洁的解决方案。

from random import randint
import datetime
import pandas as pd

date1 = datetime.date(2020,1,1).toordinal()
date2 = datetime.date(2021,1,1).toordinal()

dates = [sorted([randint(date1, date2), randint(date1, date2)]) for i in range(10)]

df = pd.DataFrame(dates, columns=["col1", "col2"])
df.col1 = df.col1.apply(lambda x: datetime.date.fromordinal(x))
df.col2 = df.col2.apply(lambda x: datetime.date.fromordinal(x))

df["col3"] = df.apply(lambda x: list(pd.date_range(start=x.col1, end=x.col2, freq="1D")), axis=1)
print(df)

输出:

         col1        col2                                               col3
0  2020-05-30  2020-07-04  [2020-05-30 00:00:00, 2020-05-31 00:00:00, 202...
1  2020-07-09  2021-01-01  [2020-07-09 00:00:00, 2020-07-10 00:00:00, 202...
2  2020-05-03  2020-10-20  [2020-05-03 00:00:00, 2020-05-04 00:00:00, 202...
3  2020-04-26  2020-06-29  [2020-04-26 00:00:00, 2020-04-27 00:00:00, 202...
4  2020-10-06  2020-11-03  [2020-10-06 00:00:00, 2020-10-07 00:00:00, 202...
5  2020-05-15  2020-12-22  [2020-05-15 00:00:00, 2020-05-16 00:00:00, 202...
6  2020-01-02  2020-02-06  [2020-01-02 00:00:00, 2020-01-03 00:00:00, 202...
7  2020-02-21  2020-09-28  [2020-02-21 00:00:00, 2020-02-22 00:00:00, 202...
8  2020-03-11  2020-07-29  [2020-03-11 00:00:00, 2020-03-12 00:00:00, 202...
9  2020-07-16  2020-07-18  [2020-07-16 00:00:00, 2020-07-17 00:00:00, 202...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多