将多个 DateTime 列合并为一列 (Python)

问题描述

我试图将我所有的日期时间信息收集到一列中。现在,我在 6 个月的跨度内为每个时期设置了一个列,但是为了进行时间序列分析,我试图将所有日期时间收集到一个列中。

这就是我累了:

 df['Dates'] = df["1 Month Date"]+ df["2 Month Date"]+ df["3 Month Date"] + df["4 Month Date"] + df["5 Month Date"] +df["6 Month Date"]

错误信息:

  TypeError: cannot add DatetimeArray and DatetimeArray

二审:

Dates = df["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]

错误信息:

KeyError: ('1 Month Date','2 Month Date','3 Month Date','4 Month Date','5 Month Date','6 Month Date')

额外信息:这是我使用 panda 导入的 excel 表,我的 1 个月日期 2 个月日期等 .. 当我执行 df.info()) 时是 datetime64[ns]

样本数据:

   1 Month Date  1 Month Room Booked 2 Month Date  2 Month Room Booked  \
0    2020-09-01                  339   2020-10-01                  346   
1    2020-09-01                    2   2020-10-01                    4   
2    2020-09-01                    4   2020-10-01                    4   
3    2020-09-01                    0   2020-10-01                    0   
4    2020-09-01                    0   2020-10-01                    0   
5    2020-09-01                    1   2020-10-01                    1   
6    2020-09-01                    2   2020-10-01                    2   
7    2020-09-01                   50   2020-10-01                   58   
8    2020-09-01                   12   2020-10-01                   12   
9    2020-09-01                    9   2020-10-01                    9   
10   2020-09-01                    6   2020-10-01                    6   
11   2021-03-01                  112   2021-04-01                  112   
12   2021-03-01                    0   2021-04-01                    0   
13   2021-02-01                   36   2021-03-01                   36   
14   2021-02-01                   18   2021-03-01                   18   
15   2021-02-01                   20   2021-03-01                   20   
16   2021-02-01                   12   2021-03-01                   12   
17   2021-02-01                    0   2021-03-01                    0   

解决方法

IIUC 使用:

Dates = df[["1 Month Date","2 Month Date","3 Month Date","4 Month Date","5 Month Date","6 Month Date"]].apply(pd.Series.explode).sum(axis=1)