Please help, Data grouping, calculating total and maximum values

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
pho7271
Posts: 12
Joined: 07 Dec 2023, 08:19

Please help, Data grouping, calculating total and maximum values

08 Apr 2024, 06:55

Data format:

Code: Select all

Aaa 1 2.02
Aaa 6 32.1
Bbb 9 23.2
Bbb 4 332.0
CCC 5 232.0
Ddd 9 22.08
Ddd 1 12.78
Ddd 2 45.34
Eee 0 456
To achieve:
When the first column is grouped by the same value, calculate the maximum value in the second column and the total value in the third column for each group after grouping
Result:

Code: Select all

aaa 6 35.12
Bbb 9 355.2
CCC 5 232.0
Ddd 9 80.2
Eee 0 456
Is there any good solution? thanks

[Mod edit: Added [code][/code] tags for better overview.]
User avatar
mikeyww
Posts: 27198
Joined: 09 Sep 2014, 18:38

Re: Please help, Data grouping, calculating total and maximum values

08 Apr 2024, 07:17

Code: Select all

#Requires AutoHotkey v2.0
str := "
(
Aaa 1 2.02
Aaa 6 32.1
Bbb 9 23.2
Bbb 4 332.0
CCC 5 232.0
Ddd 9 22.08
Ddd 1 12.78
Ddd 2 45.34
Eee 0 456
)"
maxi := Map(), sum  := Map(), out := ''
Loop Parse str, '`n', '`r'
 Loop Parse RegExReplace(A_LoopField, '\h+', ','), 'CSV'
  Switch A_Index {
   Case 1: group := A_LoopField
   Case 2: maxi[group] := maxi.Has(group) ? Max(maxi[group], A_LoopField) : A_LoopField
   Case 3: sum[group]  := sum.Has(group)  ? sum[group]     + A_LoopField  : A_LoopField
  }
For group in maxi
 out .= (out = '' ? '' : '`n') group ' ' maxi[group] ' ' Round(sum[group], 2)
MsgBox out, 'Results', 'Iconi'
image240408-0817-001.png
Output
image240408-0817-001.png (23.43 KiB) Viewed 162 times
pho7271
Posts: 12
Joined: 07 Dec 2023, 08:19

Re: Please help, Data grouping, calculating total and maximum values

08 Apr 2024, 07:49

@mikeyww
Thanks @mikeyww for getting back to me quickly
User avatar
flyingDman
Posts: 2832
Joined: 29 Sep 2013, 19:01

Re: Please help, Data grouping, calculating total and maximum values

08 Apr 2024, 11:32

If you are a fan of more compact code:

Code: Select all

gmax := map(), gsum := map(), res := ""
for x,y in strsplit(str, "`n", "`r")
	{
	z := strsplit(y," "), grp := z[1]	
	gmax[grp] := gmax.has(grp) ? max(gmax[grp],z[2]) : z[2]
	gsum[grp] := gsum.has(grp) ? gsum[grp]+z[3] 	 : z[3]
	}
For grp in gmax
	res .= grp "`t" gmax[grp] "`t" Round(gsum[grp], 2) "`n"
MsgBox trim(res,"`n"), "Results"
Same technique. I typically prefer for-loops.
14.3 & 1.3.7
pho7271
Posts: 12
Joined: 07 Dec 2023, 08:19

Re: Please help, Data grouping, calculating total and maximum values

08 Apr 2024, 22:16

Thanks @flyingDman for getting back to me

Return to “Ask for Help (v2)”

Who is online

Users browsing this forum: Leonardo_Portela, lexikos and 26 guests