【问题标题】:Get count by day given time periods在给定的时间段内按天计算
【发布时间】:2018-12-02 00:03:54
【问题描述】:

示例数据框:

    id           start1        end1      start2        end2
0  Bob       2018-11-29  2018-11-30  2018-12-01  2018-12-31
1  James     2018-10-19  2018-10-31         NaT         NaT
2  Jane      2018-04-05  2018-07-12  2018-11-29  2018-11-30

鉴于上述示例数据框,我想按月和年显示频率计数。让我们假设在这些期间,每个人 (id) 都受到了某些东西的“影响”。每个人最多有两个时间段(总会有至少一个时间段(即start1 和end1),但可能有也可能没有第二个时间段(即start2 和@987654326 @))。我想显示在任何人受到影响的整个时间范围内,按月和按年有多少人受到影响。

例如,上述数据会产生类似这样的结果(不确定年月是同一列还是多个列——不管怎样都行):

   year-month  count
0     2018-04      1
1     2018-05      1
2     2018-06      1
3     2018-07      1
4     2018-08      0
5     2018-09      0
6     2018-10      1
7     2018-11      2
8     2018-12      1

我的最终目标是在不同的时间段内查看这些数据(例如,年份(在此示例数据中均为 2018 年)、月/年、周等)。

我不确定如何将它们解压缩成一个系列,以便我可以在单个列上制作直方图。我知道一旦我将它们放在一个列中(例如,date),我可以执行以下操作:

df.groupby(df["date"].dt.month).count().plot(kind="bar")

但这只会按月计算,并且假设我已经在单列中找到了日期。

我可以只使用datetime 并继续在循环中添加天数,如果它在每个时间范围之间直到我到达结束日期,但每次我做类似的事情时,我都会知道 pandas/numpy 有更好的方法. 我正在寻找更好的方法。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    您可以先使用 pd.wide_to_long 重塑您的数据框

    from pandas.tseries.offsets import MonthEnd
    
    newdf=pd.wide_to_long(df,['start','end'],i='id',j='drop')
    newdf=newdf.apply(pd.to_datetime)
    newdf=newdf.dropna()
    newdf.start=newdf.start.values.astype('datetime64[M]')
    newdf.end=newdf.end+MonthEnd(0)
    newdf
                    start        end
    id    drop                      
    Bob   1    2018-11-01 2018-11-30
    James 1    2018-10-01 2018-10-31
    Jane  1    2018-04-01 2018-07-31
    Bob   2    2018-12-01 2018-12-31
    Jane  2    2018-11-01 2018-11-30
    

    然后我们使用date_range

    l=[pd.date_range(x,y,freq='M',closed ='right').strftime('%Y-%m') for x ,y in zip(newdf.start,newdf.end)]
    pd.Series(np.concatenate(l)).value_counts()
    2018-11    2
    2018-05    1
    2018-12    1
    2018-04    1
    2018-06    1
    2018-10    1
    2018-07    1
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 2018-07-27
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多