英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论