【问题标题】:Pandas retain only a specified sub-sequence (groupby order retain subsequence)Pandas 只保留指定的子序列(groupby order 保留子序列)
【发布时间】:2020-07-21 23:57:33
【问题描述】:

给定 Pandas 数据帧中的活动日志,其中包含在指定“时间戳”处通过一系列“动作”的“id” - 我想保留与指定动作序列相对应的行。

例如输入数据

import pandas as pd 
# Create a sample data-frame from a dictionary 
id = ['A123', 'A123', 'A123', 'A123', 'A123', 'A123', 'A234', 'A234', 'A234', 'A234', 'A341', 'A341', 'A341', 'A341', 'A341', 'A341', 'A341', 'A341', 'A341', 'A341']
action = ['A', 'B', 'C', 'D', 'B', 'A', 'B', 'A', 'C', 'D', 'D', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'B', 'C']
timestamp = ['1', '2', '3', '4', '5', '6', '1', '2', '3', '4', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
the_dict = {'id': id, 'action': action, 'timestamp': timestamp}
# This is the sample data-frame with columns:
# id    action    timestamp
# Each id when ordered by timestamp then action gives the sequence of actions taken by the id
dataFrame = pd.DataFrame(the_dict)
######################################
# Input data
######################################
#      id action timestamp
#0   A123      A         1
#1   A123      B         2
#2   A123      C         3
#3   A123      D         4
#4   A123      B         5
#5   A123      A         6
#6   A234      B         1
#7   A234      A         2
#8   A234      C         3
#9   A234      D         4
#10  A341      D         1
#11  A341      B         2
#12  A341      C         3
#13  A341      D         4
#14  A341      A         5
#15  A341      B         6
#16  A341      C         7
#17  A341      D         8
#18  A341      B         9
#19  A341      C        10

# The sequence of interest
the_sequence = ['B', 'C', 'D']

# Desired output: Group by id, order by timestamp, return all rows which match the given sequence of actions
######################################
# The output data-frame:
######################################
#      id action timestamp
#1   A123      B         2
#2   A123      C         3
#3   A123      D         4
#11  A341      B         2
#12  A341      C         3
#13  A341      D         4
#15  A341      B         6
#16  A341      C         7
#17  A341      D         8

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    您可以将.shift 逻辑用于A、B 和C。基本上,您正在检查A 在下一行中有B 和C 的行。这将返回A's。然后,对B 和C 遵循类似的协议。

    df = (df[df.groupby('id')['action'].
         apply(lambda x:
               (x == 'B') & (x.shift(-1) == 'C') & (x.shift(-2) == 'D') |
               (x == 'C') & (x.shift(1) == 'B') & (x.shift(-1) == 'D') |
               (x == 'D') & (x.shift(2) == 'B') & (x.shift(1) == 'C'))])
    df
    

    输出:

        id      action  timestamp
    1   A123    B       2
    2   A123    C       3
    3   A123    D       4
    11  A341    B       2
    12  A341    C       3
    13  A341    D       4
    15  A341    B       6
    16  A341    C       7
    17  A341    D       8
    

    【讨论】:

    • 最好是groupby + shift~
    • 我不小心做了A,B,C,稍后会更新,但它的确切逻辑是一样的,所以只是用BCD子ABC。
    • 你还需要groupby
    • 谢谢@Yorben_s,我看到了你的评论。您的意思是逻辑有问题,还是使用 .groupby 会更清晰?当我从健身房回来时,我将使用 .groupby 进行测试:)
    • @ALollz gotchya,我错过了那部分要求。回家后我会更新我的答案。
    【解决方案2】:

    如果您需要查找序列,您可以在列表理解中使用np.logical_and.reduce + shift similar to my answer here。在这种情况下,还需要考虑一个分组,但考虑到您可以使用shift 进行排序。

    这里的想法是找到所有等于序列中第一个元素的行。然后使用 shift 我们检查后面的行是否等于第二个元素(并确保它在同一组中)。 m 将为我们提供序列结束处的所有索引,因此我们可以用它形成掩码来分割原始数据帧。

    import numpy as np
    
    def find_seq_within_group(df, seq, seq_col, gp_col):
        seq = seq[::-1]  # to get last index
        m = np.logical_and.reduce([df[seq_col].shift(i).eq(seq[i]) & df[gp_col].shift(i).eq(df[gp_col]) 
                                   for i in range(len(seq))])
        
        # Return entire sequence
        m = np.logical_or.reduce([np.roll(m, -i) for i in range(len(seq))])
        
        return df.loc[m]
    

    # df = df.sort_values(['id', 'timestamp'])
    find_seq_within_group(df=df, seq=['B', 'C', 'D'], seq_col='action', gp_col='id')
    
          id action timestamp
    1   A123      B         2
    2   A123      C         3
    3   A123      D         4
    11  A341      B         2
    12  A341      C         3
    13  A341      D         4
    15  A341      B         6
    16  A341      C         7
    17  A341      D         8
    

    【讨论】:

      【解决方案3】:

      我们可以cumsum + str.contains

      m=df.groupby('id').action.apply(lambda x : (x+',').cumsum()).str.contains('B,C,D')
      nedf=df[m]
      nedf
            id action timestamp
      3   A123      D         4
      4   A123      B         5
      5   A123      A         6
      13  A341      D         4
      14  A341      A         5
      15  A341      B         6
      16  A341      C         7
      17  A341      D         8
      18  A341      B         9
      19  A341      C        10
      

      【讨论】:

        【解决方案4】:

        这可能也有帮助:

        sequence=['A','B','C','D']
        n=len(sequence)
        for i in  range(dataFrame.shape[0]):
            if(list(dataFrame['action'][i:i+n].values)==sequence):
                print ("the sequence starts at",i)
            else:
                continue
        

        【讨论】:

          猜你喜欢
          • 2021-11-01
          • 2021-05-14
          • 2015-12-08
          • 1970-01-01
          • 2013-03-17
          • 1970-01-01
          • 2016-09-01
          • 1970-01-01
          • 2020-02-06
          相关资源
          最近更新 更多