pandas按组的窗口函数

huangapple go评论79阅读模式
英文:

pandas window by groupby function

问题

我有一个pd数据框:

  1. pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  2. 'A': [1, 1, 1, 0, 0, 0, 1, 1, 0, 0],
  3. 'B': [7, 8, 4, 3, 5, 6, 3, 1, 4, 5],})

我想要创建一个滑动窗口,只要列的值为1,就找到最大值,一旦值变为0,就找到这些0的最大值。以下是期望的输出:

  1. pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  2. 'A': [1, 1, 1, 0, 0, 0, 1, 1, 0, 0],
  3. 'B': [7, 8, 4, 3, 5, 6, 3, 1, 4, 5],
  4. 'Output': [8, 8, 8, 6, 6, 6, 3, 3, 5, 5 ]})
英文:

I have a pd dataframe

  1. pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  2. 'A': [1, 1, 1, 0, 0,0, 1, 1, 0, 0],
  3. 'B': [7, 8, 4, 3, 5, 6, 3, 1, 4, 5],})

I want to do a sliding window that as long as the value of a column is 1 find the max, as soon as the value changes to 0 find the max for those 0. here is a desired output:

  1. pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  2. 'A': [1, 1, 1, 0, 0,0, 1, 1, 0, 0],
  3. 'B': [7, 8, 4, 3, 5, 6, 3, 1, 4, 5],
  4. 'Output': [8, 8, 8, 6, 6, 6, 3, 3, 5, 5 ]})

答案1

得分: 0

使用A的移位值和Series.cumsum来创建连续的分组,然后传递给GroupBy.transform,使用max函数:

  1. df['Output'] = df.groupby(df.A.ne(df.A.shift()).cumsum())['B'].transform('max')
  2. print(df)
  3. day A B Output
  4. 0 1 1 7 8
  5. 1 2 1 8 8
  6. 2 3 1 4 8
  7. 3 4 0 3 6
  8. 4 5 0 5 6
  9. 5 6 0 6 6
  10. 6 7 1 3 3
  11. 7 8 1 1 3
  12. 8 9 0 4 5
  13. 9 10 0 5 5
英文:

Create consecutive groups by A by compare with shifted values and Series.cumsum, then pass to GroupBy.transform with max:

  1. df['Output'] = df.groupby(df.A.ne(df.A.shift()).cumsum())['B'].transform('max')
  2. print (df)
  3. day A B Output
  4. 0 1 1 7 8
  5. 1 2 1 8 8
  6. 2 3 1 4 8
  7. 3 4 0 3 6
  8. 4 5 0 5 6
  9. 5 6 0 6 6
  10. 6 7 1 3 3
  11. 7 8 1 1 3
  12. 8 9 0 4 5
  13. 9 10 0 5 5

huangapple
  • 本文由 发表于 2023年6月19日 14:20:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504051.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定