查找时间范围内的现值,pandas

我正在使用一个包含不同产品的数据框(每个产品都有不同的产品参考,在此数据框中为“PR”),这些产品具有特定的工作时间范围。


import pandas as pd

import numpy as np

np.random.seed(123)

df = pd.DataFrame({ 

    'PR':("1","2","3","4","5","18"),

    'StartDate':pd.date_range('1/1/2011', periods=6, freq='D'),

    'EndDate':np.random.choice( pd.date_range('1/1/2011', periods=365, 

                          freq='D'), 6, replace=False) 

    })

打印出这个表


                PR  StartDate   EndDate

           0    1   2011-01-01  2011-03-01

           1    2   2011-01-02  2011-11-06

           2    3   2011-01-03  2011-01-10

           3    4   2011-01-04  2011-10-27

           4    5   2011-01-05  2011-08-31

           5    18  2011-01-06  2011-06-06

我想知道在任何给定月份有多少产品处于活动状态(在本例中:(2011-01,1 个产品活动),(2011-02,5 个产品活动),(2011-04,4 个产品活动)等。 .. 我怎样才能做到这一点?


桃花长相依
浏览 70回答 2
2回答

慕森卡

StartDate如果给定的产品在,范围内,您可以检查每个月EndDate。In [26]: pd.Series(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {dt: ((df.StartDate <= dt) & (df.EndDate >= dt)).sum()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for dt in pd.date_range(start='2011-01-01', freq='1MS', periods=6)})Out[26]:&nbsp; &nbsp; &nbsp; &nbsp;2011-01-01&nbsp; &nbsp; 12011-02-01&nbsp; &nbsp; 52011-03-01&nbsp; &nbsp; 52011-04-01&nbsp; &nbsp; 42011-05-01&nbsp; &nbsp; 42011-06-01&nbsp; &nbsp; 4dtype: int64&nbsp; &nbsp;

慕慕森

这是另一种方法:df.assign(dates = [pd.date_range(s,f, freq='MS') for s, f in zip(df['StartDate'], df['EndDate'])])\&nbsp; .explode('dates').groupby('dates')['PR'].nunique()输出:dates2011-01-01&nbsp; &nbsp; 12011-02-01&nbsp; &nbsp; 52011-03-01&nbsp; &nbsp; 52011-04-01&nbsp; &nbsp; 42011-05-01&nbsp; &nbsp; 42011-06-01&nbsp; &nbsp; 42011-07-01&nbsp; &nbsp; 32011-08-01&nbsp; &nbsp; 32011-09-01&nbsp; &nbsp; 22011-10-01&nbsp; &nbsp; 22011-11-01&nbsp; &nbsp; 1Name: PR, dtype: int64
打开App,查看更多内容
随时随地看视频慕课网APP