每日最长连续条纹的矢量化计数

时间:2019-07-10 13:35:20

标签: python pandas

对于评估电厂的每日最长连续运行时间,我必须评估每天的最长连续时间,这意味着每天被视为一个单独的时间表。

因此,假设我在数据帧df中获得了功率输出:

df = pd.Series(
    data=[
        *np.zeros(4), *(np.full(24*5, 19.5) + np.random.rand(24*5)), 
        *np.zeros(4), *(np.full(8, 19.5) + np.random.rand(8)), 
        *np.zeros(5), *(np.full(24, 19.5) + np.random.rand(24)), 
        *np.zeros(27), *(np.full(24, 19.5) + np.random.rand(24))], 
    index=pd.date_range(start='2019-07-01 00:00:00', periods=9*24, freq='1h'))

“截止功率”为1(低于此值的所有东西均视为关闭)。我用它来掩盖“ on”值,将其移位并将其与自身进行比较以计算连续groups的数量。最后,我将groups按索引中的年份分组,并计算每日的连续值consec_group

mask = df > 1
groups = mask.ne(mask.shift()).cumsum()
consec_group = groups[mask].groupby(groups[mask].index.date).value_counts()

哪种产量:

consec_group
Out[3]: 
2019-07-01  2    20
2019-07-02  2    24
2019-07-03  2    24
2019-07-04  2    24
2019-07-05  2    24
2019-07-06  4     8
            2     4
            6     3
2019-07-07  6    21
2019-07-09  8    24
dtype: int64

但是我想让每个连续的每日条纹的最大值和没有任何运行时间的日期都显示为零,如2019-07-08 7 0。查看预期结果:

2019-07-01    20
2019-07-02    24
2019-07-03    24
2019-07-04    24
2019-07-05    24
2019-07-06     8
2019-07-07    21
2019-07-08     0
2019-07-09    24
dtype: int64

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

首先通过Series.reset_index删除第二级,通过使用Series.asfreq进行回叫过滤出第二个重复的值-之所以起作用,是因为./gradlew assembleDebugAndroidTest -DtestBuildType=debug -DTURBO_TEST_APK .value_counts进行了排序:

Series

或使用GroupBy.first解决方案:

consec_group = (consec_group.reset_index(level=1, drop=True)[lambda x: ~x.index.duplicated()]
                            .asfreq('d', fill_value=0))
print (consec_group)

consec_group = (consec_group.groupby(level=0)
                            .first() 
                            .asfreq('d', fill_value=0))

答案 1 :(得分:1)

好吧,我想我离终点线太近了,看不到答案……看来我已经解决了复杂的部分。
因此,在发布问题之后,我用max参数而不是level=0测试了level=1,这就是解决方案:

max_consec_group = consec_group.max(level=0).asfreq('d', fill_value=0)

感谢jezrael的asfreq部分!

相关问题