Ksh*_*dav 4 python numpy date pandas
我有一个数据框,其中有两个日期列:
Date1 Date2
2018-10-02 2018-12-21
2019-01-20 2019-04-30
Run Code Online (Sandbox Code Playgroud)
等等
我想创建第三列,该列基本上是包含两个日期之间所有月份的列,如下所示:
Date1 Date2 months
2018-10-02 2018-12-21 201810
2018-10-02 2018-12-21 201811
2018-10-02 2018-12-21 201812
2019-01-20 2019-04-30 201901
2019-01-20 2019-04-30 201902
2019-01-20 2019-04-30 201903
2019-01-20 2019-04-30 201904
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我尝试使用此公式:
df['months']=df.apply(lambda x: pd.date_range(x.Date1,x.Date2, freq='MS').strftime("%Y%m"))
Run Code Online (Sandbox Code Playgroud)
但我没有得到理想的结果。请帮助。谢谢
使用 merge
final = df.merge(df.apply(lambda s: pd.date_range(s.Date1, s.Date2, freq='30D'), 1)\
.explode()\
.rename('Months')\
.dt.strftime('%Y%m'),
left_index=True,
right_index=True)
Run Code Online (Sandbox Code Playgroud)
Months Date1 Date2
0 201810 2018-10-02 2018-12-21
0 201811 2018-10-02 2018-12-21
0 201812 2018-10-02 2018-12-21
1 201901 2019-01-20 2019-04-30
1 201902 2019-01-20 2019-04-30
1 201903 2019-01-20 2019-04-30
1 201904 2019-01-20 2019-04-30
Run Code Online (Sandbox Code Playgroud)