大Pandas连续几周的最长纪录

2024-05-16 08:04:59 发布

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

目前,我正在处理不同科目的每周数据,但可能会有一些没有数据的长时间连续记录,所以,我想做的是,每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

我的预期产出是:

^{pr2}$

我有点接近,试图在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

有什么想法可以实现我想要的吗?在


Tags: 数据方法标记iddfshift记录nan
2条回答

虽然不如“斯科特伯顿”简洁,但我喜欢这种方法

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

试试这个:

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]

输出:

^{pr2}$

相关问题 更多 >