在熊猫中,组连续几周获得最长的连胜



目前我正在使用每周的数据来处理不同主题,但是它可能没有一些没有数据的条纹,因此,我想做的就是保持最长的连续连续状态每个id的几周。我的数据看起来像:

id    week
1      8
1      15
1      60
1      61
1      62
2      10
2      11
2      12
2      13
2      25
2      26

我的预期输出将是:

id    week
1      60
1      61
1      62
2      10
2      11
2      12
2      13

我有点近,试图用1 week == week.shift()+1标记1。问题是这种方法没有标志着第一次出现在条纹中,而且我也无法过滤最长的方法:

df.loc[ (df['id'] == df['id'].shift())&(df['week'] == df['week'].shift()+1),'streak']=1

根据我的例子,这将带来以下方式:

id    week  streak
1      8     nan
1      15    nan
1      60    nan
1      61    1
1      62    1
2      10    nan
2      11    1
2      12    1
2      13    1
2      25    nan
2      26    1

关于如何实现我想要的东西的任何想法?

尝试以下:

df['consec'] = df.groupby(['id',df['week'].diff(-1).ne(-1).shift().bfill().cumsum()]).transform('count')
df[df.groupby('id')['consec'].transform('max') == df.consec]

输出:

   id  week  consec
2   1    60       3
3   1    61       3
4   1    62       3
5   2    10       4
6   2    11       4
7   2    12       4
8   2    13       4

不像@scottboston那样简洁,但我喜欢这种方法

def max_streak(s):
  a = s.values    # Let's deal with an array
  # I need to know where the differences are not `1`.
  # Also, because I plan to use `diff` again, I'll wrap
  # the boolean array with `True` to make things cleaner
  b = np.concatenate([[True], np.diff(a) != 1, [True]])
  # Tell the locations of the breaks in streak
  c = np.flatnonzero(b)
  # `diff` again tells me the length of the streaks
  d = np.diff(c)
  # `argmax` will tell me the location of the largest streak
  e = d.argmax()
  return c[e], d[e]
def make_thing(df):
  start, length = max_streak(df.week)
  return df.iloc[start:start + length].assign(consec=length)
pd.concat([
  make_thing(g) for _, g in df.groupby('id')    
])
   id  week  consec
2   1    60       3
3   1    61       3
4   1    62       3
5   2    10       4
6   2    11       4
7   2    12       4
8   2    13       4

最新更新