在Python中选择满足某些条件的行之间的行

时间:2017-11-14 11:20:48

标签: python pandas

我有一个大型的pandas数据框,我想选择条目(action1 == 0)和退出点(action1 == 1)之间发生的所有用户操作。数据库中有多个这样的用户会话。它看起来像这样:

User_action   Reference   Other_data  Row_index
  action2         0          foo         a
  action1         0          bar         b
  action6         0          foo         c
  action4         0          foo         d
  action1         1          bar         e
  action7         0          foo         f
  action1         0          foo         g
  action3         0          bar         h
  action1         1          foo         i
  action1         1          foo         j
  action3         0          bar         k
  action1         0          foo         l
  action9         0          foo         m
  action1         1          foo         n

结果应该产生具有索引的行:c,d,h和m:

User_action   Reference   Other_data  Row_index
  action6         0          foo         c
  action4         0          foo         d
  action3         0          bar         h
  action9         0          foo         m

1 个答案:

答案 0 :(得分:1)

使用:

#filter only category
df1 = df[df['User_action'] == 'action1'].copy()

#test only pairs 0, 1 and reindex for same length as original df
m1 = df1['Reference'].eq(1) & df1['Reference'].shift(1).eq(0)
m1 = m1.reindex(df.index, fill_value=False)
m2 = df1['Reference'].eq(0) & df1['Reference'].shift(-1).eq(1)
m2 = m2.reindex(df.index, fill_value=False).shift().fillna(False)

a = np.select([m1, m2], [-1,1], default=0)
m = a.cumsum() == 1
#filter by final condition
df = df[m]

print (df)
   User_action  Reference Other_data Row_index
4      action6          0        foo         c
5      action4          0        foo         d
9      action3          0        bar         h
14     action9          0        foo         m
相关问题