Python Pandas:创建包含日期范围的新列

时间:2020-08-18 13:53:26

标签: python pandas

我有2列的酒店DataFrame:入住和退房。我想创建一个新的列,其中包含一系列日期,从签入到签出。

enter image description here

示例:签入= 2019-10-02,签出= 2019-10-04。 新列应具有日期系列:2019-10-02、2019-10-03、2019-10-04。对每行应用相同的逻辑。请告知我如何使用Python Pandas。

2 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

df['check_in'] = pd.to_datetime(df['check_in'])
df['check_out'] = pd.to_datetime(df['check_out'])
df['range'] = df.apply(lambda x: list(pd.date_range(x['check_in'], x['check_out'])), axis=1)
print(df)

    check_in  check_out                                              range
0 2019-10-02 2019-10-04  [2019-10-02 00:00:00, 2019-10-03 00:00:00, 201...

答案 1 :(得分:0)

假设两个列都在日期时间序列中可用。

下面的代码应为您提供必填格式的范围,并带有新列。

df['range'] = df.apply(lambda x: pd.date_range(x['check_in'], x['check_out']).format('%Y-%m-%d')[1:], axis=1)
相关问题