Python 基于日期列和日期范围填充数据框

Python 基于日期列和日期范围填充数据框,python,pandas,Python,Pandas,我有一个熊猫数据框,看起来像这样 id start end 0 1 2020-02-01 2020-04-01 1 2 2020-04-01 2020-04-28 id start end 0 1 2020-02-01 2020-02-20 1 1 2020-04-01 2020-05-10 2 2 2020-04-10 2020-04-28 我还有两个额外的参数是日期值,比如x和y。x和y总

我有一个熊猫数据框,看起来像这样

    id     start    end
0   1   2020-02-01  2020-04-01
1   2   2020-04-01  2020-04-28
    id     start       end
0   1   2020-02-01  2020-02-20
1   1   2020-04-01  2020-05-10
2   2   2020-04-10  2020-04-28
我还有两个额外的参数是日期值,比如x和y。x和y总是一个月的第一天

我想将上述数据框扩展到如下所示的x=“2020-01-01”和y=“2020-06-01”

数据帧已扩展,因此对于每个id,(x,y)行之间将有额外的月份。创建状态列并填写值,以便

  • 如果月列值等于开始列的月份,则填充状态为1
  • 如果月份列值大于起始列的月份,但小于或等于结束列的月份,则将其填充为2
  • 如果月列值小于起始月的月份,则将其填充为-1。此外,如果“月份”列的值大于“结束填充状态月份”,则为-1
我试图在熊猫身上解决这个问题,而不是循环。我目前的解决方案是使用循环,使用大型数据集运行需要更长的时间

这里有什么能帮我的吗

感谢@Code Different提供的解决方案。它解决了这个问题。然而,问题的一个扩展是,数据帧可能是这样的

    id     start    end
0   1   2020-02-01  2020-04-01
1   2   2020-04-01  2020-04-28
    id     start       end
0   1   2020-02-01  2020-02-20
1   1   2020-04-01  2020-05-10
2   2   2020-04-10  2020-04-28

一个id可以有多个条目。对于上述相隔6个月的x和y,我希望数据帧中每个id有6行。该解决方案目前为dataframe中的每一行创建6行。在处理具有数百万ID的数据帧时,这是可以的,但并不理想。

确保
开始
结束
列的类型为
时间戳

# Explode each month between x and y
x = '2020-01-01'
y = '2020-06-01'

df['month'] = [pd.date_range(x, y, freq='MS')] * len(df)
df = df.explode('month').drop_duplicate(['id', 'month'])

# Determine the status
df['status'] = -1

cond = df['start'] == df['month']
df.loc[cond, 'status'] = 1

cond = (df['start'] < df['month']) & (df['month'] <= df['end'])
df.loc[cond, 'status'] = 2
#每月在x和y之间爆炸
x='2020-01-01'
y='2020-06-01'
df['month']=[pd.date_range(x,y,freq='MS')]*len(df)
df=df.explode('month')。删除重复项(['id','month'])
#确定状态
df['status']=-1
cond=df['start']==df['month']
df.loc[cond,'status']=1

cond=(df['start']