pandas按组的窗口函数

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

pandas window by groupby function

问题

我有一个pd数据框:

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

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

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

I have a pd dataframe

pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
              'A': [1, 1, 1, 0, 0,0, 1, 1, 0, 0],
              '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:

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

答案1

得分: 0

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

df['Output'] = df.groupby(df.A.ne(df.A.shift()).cumsum())['B'].transform('max')
print(df)
   day  A  B  Output
0    1  1  7       8
1    2  1  8       8
2    3  1  4       8
3    4  0  3       6
4    5  0  5       6
5    6  0  6       6
6    7  1  3       3
7    8  1  1       3
8    9  0  4       5
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:

df['Output'] = df.groupby(df.A.ne(df.A.shift()).cumsum())['B'].transform('max')
print (df)
   day  A  B  Output
0    1  1  7       8
1    2  1  8       8
2    3  1  4       8
3    4  0  3       6
4    5  0  5       6
5    6  0  6       6
6    7  1  3       3
7    8  1  1       3
8    9  0  4       5
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:

确定