+

Python | Pandas dataframe.mean ()

The Pandas function dataframe.mean() returns the average value for the requested axis. If the method is applied to a panda series object, the method returns a scalar value that is the average of all observations in the data frame. When applied to a pandas data object, the method returns a pandas series object that contains the average along the specified axis.

Syntax: DataFrame.mean (axis = None, skipna = None, level = None, numeric_only = None, ** kwargs)

Parameters:
axis: {index (0), columns (1)}
skipna: Exclude NA / null values ​​when computing the result

level: If the axis is a MultiIndex ( hierarchical), count along a particular level, collapsing into a Series

numeric_only: Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.

Returns: mean: Series or DataFrame (if level specified)

Example # 1: Use the mean () function to find the average of all observations along the index axis.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , 44 1 ],

  "B" : [ 5 , 2 , 54 , 3 , 2 ], 

"C" : [ 20 , 16 , 7 , 3 , 8 ],

"D" : [ 14 , 3 , 17 , 2 , 6 ]})

 
# Print the data frame
df

Let`s use the dataframe.mean () function to find average value along the index axis.

# Even if we don`t specify axis = 0,
# the method will return the average
# default index axis

df.mean (axis = 0 )

Output:

Example # 2: Use the mean () function on a data frame that has Na values. Also find the mean along the column axis.

# import pandas as pd

import pandas as pd

 
# Create data frame

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ],

"B " : [ 7 , 2 , 54 , 3 , None ],

"C" : [ 20 , 16 , 11 , 3 , 8 ] ,. 

"D" : [ 14 , 3 , None , 2 , 6 ]})

  
# skip Na values ​​when looking for mean

df.mean (axis = 1 , skipna = True )

Output:

Get Solution for free from DataCamp guru