首页 > 解决方案 > 在时间范围内查找现值,熊猫

问题描述

我正在使用具有不同产品的数据框(每个产品都有不同的产品参考,在此数据框中为“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 个产品存活)等。 .. 我怎样才能做到这一点?

标签: pythonpandastime

解决方案


您可以检查每个月,如果给定的产品在StartDate,EndDate范围内。

In [26]: pd.Series(
            {dt: ((df.StartDate <= dt) & (df.EndDate >= dt)).sum()
             for dt in pd.date_range(start='2011-01-01', freq='1MS', periods=6)})
Out[26]:       
2011-01-01    1
2011-02-01    5
2011-03-01    5
2011-04-01    4
2011-05-01    4
2011-06-01    4
dtype: int64   

推荐阅读