Issue
i'm trying to create columns to represent min/max after every row within a group.
original df
╔═══════╦═══════╦════════╗ ║ color ║ panel ║ result ║ ╠═══════╬═══════╬════════╣ ║ blue ║ b ║ 4 ║ ║ blue ║ b ║ 3 ║ ║ blue ║ b ║ 3 ║ ║ blue ║ b ║ 5 ║ ║ blue ║ b ║ 4 ║ ║ blue ║ b ║ 7 ║ ║ blue ║ b ║ 1 ║ ║ blue ║ b ║ 5 ║ ║ blue ║ b ║ 3 ║ ║ blue ║ b ║ 2 ║ ╚═══════╩═══════╩════════╝
result trying to get
╔═══════╦═══════╦════════╦═════╦═════╗ ║ color ║ panel ║ result ║ min ║ max ║ ╠═══════╬═══════╬════════╬═════╬═════╣ ║ blue ║ b ║ 4 ║ 4 ║ 4 ║ ║ blue ║ b ║ 3 ║ 3 ║ 4 ║ ║ blue ║ b ║ 3 ║ 3 ║ 4 ║ ║ blue ║ b ║ 5 ║ 3 ║ 5 ║ ║ blue ║ b ║ 4 ║ 3 ║ 5 ║ ║ blue ║ b ║ 7 ║ 3 ║ 7 ║ ║ blue ║ b ║ 1 ║ 1 ║ 7 ║ ║ blue ║ b ║ 5 ║ 1 ║ 7 ║ ║ blue ║ b ║ 3 ║ 1 ║ 7 ║ ║ blue ║ b ║ 2 ║ 1 ║ 7 ║ ╚═══════╩═══════╩════════╩═════╩═════╝
data = {'color':['blue','blue','blue','blue','blue','blue','blue','blue','blue','blue'],
'panel':['b','b','b','b','b','b','b','b','b','b'],
'result':[4,3,3,5,4,7,1,5,3,2]}
kindly advise. thank you
Solution
Use GroupBy.agg
with GroupBy.cummax
and
GroupBy.cummin
and assign to new columns (it is possible, because output is DataFrame with same size like original):
df[['min','max']] = df.groupby(['color','panel'])['result'].agg(['cummin','cummax'])
print (df)
color panel result min max
0 blue b 4 4 4
1 blue b 3 3 4
2 blue b 3 3 4
3 blue b 5 3 5
4 blue b 4 3 5
5 blue b 7 3 7
6 blue b 1 1 7
7 blue b 5 1 7
8 blue b 3 1 7
9 blue b 2 1 7
Answered By - jezrael
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.