Home > database >  How to get average of a list in pandas dataframe
How to get average of a list in pandas dataframe

Time:05-19

Here is my dataframe. I am looking to calculate the average of the current, voltage, and power of each switch individually.

                  switch12            switch11            switch10
Current  [0.1, 0.12, 0.15]  [0.15, 0.11, 0.13]  [0.18, 0.17, 0.15]
Voltage         [120, 118]          [120, 116]          [120, 117]
Power             [12, 25]            [18, 19]        [21.6, 22.4]

looking to have the output be something like this:

                  switch12            switch11            switch10
Current              0.123               0.130               0.167
Voltage                119                 118               118.5
Power                 18.5                18.5                22.0

if there is another method which does not utilize pandas to help with this I am open to hearing about that too

CodePudding user response:

Another method:

out = df.explode([*df.columns]).groupby(level=0).mean()
print(out)

Prints:

           switch12  switch11    switch10
Current    0.123333      0.13    0.166667
Power     18.500000     18.50   22.000000
Voltage  119.000000    118.00  118.500000

CodePudding user response:

Try applymap

df = df.applymap(np.mean)

# or

df = df.applymap(lambda l: sum(l) / len(l))
print(df)

     switch12  switch11    switch13
0    0.123333      0.13    0.166667
1  119.000000    118.00  118.500000
2   18.500000     18.50   22.000000
  • Related