Home > Mobile >  Getting min and max after every row in padas dataframe
Getting min and max after every row in padas dataframe

Time:11-03

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

CodePudding user response:

You want cummin and cummax

data.result.cummin()
data.result.cummax()

CodePudding user response:

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
  • Related