user8149657 user8149657 -4 years ago 56
Python Question

How to use python list to group elements and average the group numbers?

How to use python list to group elements and average the group numbers?
I have a list [1_1 34 1_1 45 1_1 78 2_1 33 2_1 12 3_2 78 3_1 90 1_3 65 1_2 98 1_3 62 1_3 54 1_3 48 1_3 28 1_2 21 1_2 35] the first element is a group name and second element is a number.
how can I put them in a grouping such [1_1 34 1_1 45 1_1 78 1_2 21 1_2 35 1_3 62.....]
then average by grouping, such [1_1 52.3 1_2 28 1_3 34 .......]

thank you

OK, let me clarify a little about this. I had a test result looks like this and I want to use python to group them and show the average on each group. thank you.

1_1 32
1_1 13
1_1 13
1_1 31
1_3 13
1_1 35
1_2 41
1_1 19
1_2 64
1_3 23
1_2 23
1_2 22
1_2 67
1_2 41
1_3 40
1_1 35
1_2 20
1_2 35
1_3 69
1_2 67
1_3 68
1_1 21
1_3 70
1_3 23
1_3 47
1_3 38
1_3 67
1_3 13
1_2 13
1_2 22
1_3 22
1_3 35
1_3 14
1_3 68
1_2 67
1_3 65
1_3 13
1_3 41
1_3 67
1_3 22
1_3 67
1_2 22
1_2 42
1_2 13
1_3 66
1_3 68
1_3 67
1_2 66
1_3 13
1_3 68
1_2 39

Answer Source

lets say

indexes=['1_1','1_1','1_1','2_1','2_1','3_2','3_1','1_3','1_2','1_3','1_3','1_3','1_3','1_2','1_2']
values=[34,45,78,33,12,78,90,65,98,62,54,48,28,21,35]

grouping is fun with pandas

import pandas as pd

create a dataframe with index and values

df=pd.DataFrame(values,columns=["values"],index=indexes)

now groupby the index and do mean

df.groupby(df.index).mean()

result looks like:

        values
1_1     52.333333
1_2     51.333333 
1_3     51.400000
2_1     22.500000
3_1     90.000000
3_2     78.000000
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download