简体   繁体   English

python将日期列表与数据框中的起始和结束日期列进行比较

[英]python compare date list to start and end date columns in dataframe

Problem: I have a dataframe with two columns: Start date and End date. 问题:我有一个包含两列的数据框:开始日期和结束日期。 I also have a list of dates. 我还有一份日期清单。 So lets say the data looks something like this: 所以假设数据看起来像这样:

data = [[1/1/2018,3/1/2018],[2/1/2018,3/1/2018],[4/1/2018,6/1/2018]]
df = pd.DataFrame(data,columns=['startdate','enddate'])

dates=[1/1/2018,2/1/2018]

What I need to do is: 我需要做的是:

1)Create a new column for each date in the dates list 1)为日期列表中的每个日期创建一个新列

2)for each row in the df, if the date for the new column created is in between the start and end date, assign a 1; 2)对于df中的每一行,如果创建的新列的日期在开始日期和结束日期之间,则分配1; if not, assign a 0. 如果没有,请指定0。

I have tried to use zip but then I realized that the df rows will be thousands of rows, where as the dates list will contain about 24 items (spanning 2 years), so it stops when the dates list is exhausted, ie, at 24. 我曾尝试使用zip但后来我意识到df行将是数千行,其中日期列表将包含大约24个项目(跨越2年),因此当日期列表用尽时,即24时,它会停止。

So below is what the original df looks like and how it should look like afterwards: 所以下面是原始df的样子以及之后的样子:

Before: 之前:

   startdate    enddate
0 2018-01-01 2018-03-01
1 2018-02-01 2018-03-01
2 2018-04-01 2018-06-01

After: 后:

  startdate   enddate 1/1/2018 2/1/2018
0  1/1/2018  3/1/2018        1        1
1  2/1/2018  3/1/2018        0        1
2  4/1/2018  6/1/2018        0        0

Any help on this would be much appreciated, thanks! 任何有关这方面的帮助将非常感谢,谢谢!

Using numpy broadcast 使用numpy广播

s1=df.startdate.values
s2=df.enddate.values
v=pd.to_datetime(pd.Series(dates)).values[:,None]


newdf=pd.DataFrame(((s1<=v)&(s2>=v)).T.astype(int),columns=dates,index=df.index)
pd.concat([df,newdf],axis=1)
   startdate    enddate  1/1/2018  2/1/2018
0 2018-01-01 2018-03-01         1         1
1 2018-02-01 2018-03-01         0         1
2 2018-04-01 2018-06-01         0         0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM