Python:转置数据以在两个日期之间创建每月的记录

smb*_*smb 4 python numpy date python-3.x pandas

我有一个如下的数据集:

Category    Date 1     Date 2 
a         2017-01-01  2017-08-01
Run Code Online (Sandbox Code Playgroud)

我想要做的是转置这些数据,以便我在两个日期之间每个月都有一个记录,例如

Category Date
a        2017-01-01
a        2017-02-01
a        2017-03-01
.....
a        2017-08-01
Run Code Online (Sandbox Code Playgroud)

我需要在python中执行此操作,我的数据已经在pandas数据帧中.日期采用日期戳格式YYYY-MM-DD

piR*_*red 6

使用理解 pd.date_range

pd.DataFrame(
    [[c, d] for c, d1, d2 in df.itertuples(index=False)
     for d in pd.date_range(d1, d2, freq='MS')],
    columns=['Category', 'Date']
)

  Category       Date
0        a 2017-01-01
1        a 2017-02-01
2        a 2017-03-01
3        a 2017-04-01
4        a 2017-05-01
5        a 2017-06-01
6        a 2017-07-01
7        a 2017-08-01
Run Code Online (Sandbox Code Playgroud)

如果你有超过3列,你想要CategoryDate

pd.DataFrame(
    [[c, d] for c, d1, d2, *_ in df.itertuples(index=False)
     for d in pd.date_range(d1, d2, freq='MS')],
    columns=['Category', 'Date']
)
Run Code Online (Sandbox Code Playgroud)

*_解包的元组的剩余部分.


否则,我们可以捕获整个元组,只需抓住我们需要的位.

pd.DataFrame(
    [[t[0], d] for t in df.itertuples(index=False)
     for d in pd.date_range(t[1], t[2], freq='MS')],
    columns=['Category', 'Date']
)
Run Code Online (Sandbox Code Playgroud)