Pandas Dataframe查找间隔和计数出现

时间:2017-11-28 09:14:24

标签: python pandas dataframe pandas-groupby

我得到了一个混合事件的不同事件列表。例如,event1可能会发生三次,然后是另一个事件,稍后会再次发生在事件1上。

我需要的是每个事件的间隔以及这些间隔中该事件的发生次数。

values = {
        '2017-11-28 11:00': 'event1',
        '2017-11-28 11:01': 'event1',
        '2017-11-28 11:02': 'event1',
        '2017-11-28 11:03': 'event2',
        '2017-11-28 11:04': 'event2',
        '2017-11-28 11:05': 'event1',
        '2017-11-28 11:06': 'event1',
        '2017-11-28 11:07': 'event1',
        '2017-11-28 11:08': 'event3',
        '2017-11-28 11:09': 'event3',
        '2017-11-28 11:10': 'event2',
        }

import pandas as pd
df = pd.DataFrame.from_dict(values, orient='index').reset_index()
df.columns = ['time', 'event']
df['time'] = df['time'].apply(pd.to_datetime)
df.set_index('time', inplace=True)
df.sort_index(inplace=True)
df.head()

预期结果是:

occurrences = [
        {'start':'2017-11-28 11:00',
         'end':'2017-11-28 11:02',
         'event':'event1',
         'count':3},
        {'start':'2017-11-28 11:03',
         'end':'2017-11-28 11:04',
         'event':'event2',
         'count':2},
        {'start':'2017-11-28 11:05',
         'end':'2017-11-28 11:07',
         'event':'event1',
         'count':3},
        {'start':'2017-11-28 11:08',
         'end':'2017-11-28 11:09',
         'event':'event3',
         'count':2},
        {'start':'2017-11-28 11:10',
         'end':'2017-11-28 11:10',
         'event':'event2',
         'count':1},
        ]

我正在考虑使用 pd.merge_asof 查找间隔的开始/结束时间,并使用 pd.cut as explained here)< strong> groupby和count 。但不知怎的,我被卡住了。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

In [68]: x = df.reset_index()

In [69]: (x.groupby(x.event.ne(x.event.shift()).cumsum())
    ...:   .apply(lambda x:
    ...:             pd.DataFrame({
    ...:                 'start':[x['time'].min()],
    ...:                 'end':[x['time'].min()],
    ...:                 'event':[x['event'].iloc[0]],
    ...:                 'count':[len(x)]})
    ...:         )
    ...:   .reset_index(drop=True)
    ...:   .to_dict('r')
    ...: )
Out[69]:
[{'count': 3,
  'end': Timestamp('2017-11-28 11:00:00'),
  'event': 'event1',
  'start': Timestamp('2017-11-28 11:00:00')},
 {'count': 2,
  'end': Timestamp('2017-11-28 11:03:00'),
  'event': 'event2',
  'start': Timestamp('2017-11-28 11:03:00')},
 {'count': 3,
  'end': Timestamp('2017-11-28 11:05:00'),
  'event': 'event1',
  'start': Timestamp('2017-11-28 11:05:00')},
 {'count': 2,
  'end': Timestamp('2017-11-28 11:08:00'),
  'event': 'event3',
  'start': Timestamp('2017-11-28 11:08:00')},
 {'count': 1,
  'end': Timestamp('2017-11-28 11:10:00'),
  'event': 'event2',
  'start': Timestamp('2017-11-28 11:10:00')}]
如果您想将time列作为字符串,请

或以下内容:

In [75]: (x.groupby(x.event.ne(x.event.shift()).cumsum())
    ...:   .apply(lambda x:
    ...:             pd.DataFrame({
    ...:                 'start':[x['time'].min().strftime('%Y-%m-%d %H:%M:%S')],
    ...:                 'end':[x['time'].min().strftime('%Y-%m-%d %H:%M:%S')],
    ...:                 'event':[x['event'].iloc[0]],
    ...:                 'count':[len(x)]})
    ...:         )
    ...:   .reset_index(drop=True)
    ...:   .to_dict('r')
    ...: )
Out[75]:
[{'count': 3,
  'end': '2017-11-28 11:00:00',
  'event': 'event1',
  'start': '2017-11-28 11:00:00'},
 {'count': 2,
  'end': '2017-11-28 11:03:00',
  'event': 'event2',
  'start': '2017-11-28 11:03:00'},
 {'count': 3,
  'end': '2017-11-28 11:05:00',
  'event': 'event1',
  'start': '2017-11-28 11:05:00'},
 {'count': 2,
  'end': '2017-11-28 11:08:00',
  'event': 'event3',
  'start': '2017-11-28 11:08:00'},
 {'count': 1,
  'end': '2017-11-28 11:10:00',
  'event': 'event2',
  'start': '2017-11-28 11:10:00'}]

答案 1 :(得分:0)

这是两个解决方案。第一个是基于vivek-harikrishnanexplained here提供的链接。它为间隔创建连续数字,并在这些间隔内累计计算出现次数。

#%% first solution

# create intervals and count occurrences per interval
df['interval'] = (df['event'] != df['event'].shift(1)).astype(int).cumsum()
df['count'] = df.groupby(['event', 'interval']).cumcount() + 1

# now group by intervals
df.groupby('interval').last()

第二种解决方案基于maxu给出的上述答案。与第一个想法类似,它也会创建区间数,但也会找到此类区间的开始/结束时间戳。

#%% second solution

df = df.reset_index()
# create intervals
df = df.groupby(df['event'].ne(df['event'].shift()).cumsum())
# calc start/end times and count occurances at the same time
df.apply(lambda x: pd.DataFrame({
                    'start':[x['time'].min()], 
                    'end':[x['time'].max()],
                    'event':[x['event'].iloc[0]],
                    'count':[len(x)]})).reset_index(drop=True)