python - 在时间范围内查找现值,熊猫
问题描述
我正在使用具有不同产品的数据框(每个产品都有不同的产品参考,在此数据框中为“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 个产品存活)等。 .. 我怎样才能做到这一点?
解决方案
您可以检查每个月,如果给定的产品在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
推荐阅读
- reinforcement-learning - OpenAI Gym 在外部控制的环境中踏步
- swift - 快速向上滚动时,UITableViewCells 在标题后面可见
- django - Django:创建电子邮件登录字段而不是用户名后,超级用户和用户无法登录到管理员和用户页面
- python - 循环遍历一个 numpy 数组,将内容汇总到另一个数组
- java - 创建一个基本的 MVP Android 应用程序
- javascript - 我正在尝试制作一个简单的程序,每次用户单击按钮时都会增加一个数字
- node.js - mongoDB请求的附加层的好做法是什么
- javascript - 返回与鼠标靠近中心一样大的值的函数
- c - 从阶乘递归中理解这个输出
- java - 流以保存地图名称和使用该名称签名的对象的数量