Home > Enterprise >  What is the lambda function to compute mean of each column/row in a dataframe (pandas)?
What is the lambda function to compute mean of each column/row in a dataframe (pandas)?

Time:09-27

What is the lambda function to compute the mean of each column/row in a data frame (pandas)?

I am trying to get the mean of each column of my data frame by lambda function.

CodePudding user response:

You can use a lot of methods like, for a single column:

df['column'].mean() # enter column name in string format

Or you can use df.descibe() to get all information per column like mean,standard deviation e.t.c...

df.describe()

CodePudding user response:

This is a lambda function to compute the mean of each column (if you want to compute the mean of each row just put axis=1):

import pandas as pd

df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5},
                   {'a': 20, 'b': 10, 'c': 7},
                   {'a': 25, 'b': 30, 'c': 9}])

df.apply(lambda col: sum(col) / len(col), axis=0)

This is the result:

a    20.000000
b    18.333333
c     7.000000
dtype: float64
  • Related