在Python中满足特定条件的行之间选择行

2024-04-26 04:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大熊猫数据帧,我想选择在入口(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

Tags: 用户dataindexfoobaractionrowreference
1条回答
网友
1楼 · 发布于 2024-04-26 04:30:49

用途:

#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

相关问题 更多 >