pandas.DataFrame.mean#
Return the mean of the values over the requested axis.
Parameters axis
Axis for the function to be applied on. For Series this parameter is unused and defaults to 0.
skipna bool, default True
Exclude NA/null values when computing the result.
level int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.
Deprecated since version 1.3.0: The level keyword is deprecated. Use groupby instead.
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Deprecated since version 1.5.0: Specifying numeric_only=None is deprecated. The default value will be False in a future version of pandas.
Среднее значение mean() в DataFrame Pandas
В этом примере мы рассчитаем среднее значение по столбцам. Мы узнаем средние оценки, полученные студентами по предметам.
Функция mean() возвращает Pandas, это поведение функции mean() по умолчанию. Следовательно, в этом конкретном случае вам не нужно передавать какие-либо аргументы функции mean(). Или, если вы хотите явно указать функцию для вычисления по столбцам, передайте axis = 0, как показано ниже.
Пример 2
В этом примере мы создадим DataFrame с числами, присутствующими во всех столбцах, и вычислим среднее значение.
Из предыдущего примера мы видели, что функция mean() по умолчанию возвращает среднее значение, вычисленное среди столбцов.
Пример 3: по строкам
В этом примере мы вычислим среднее значение всех столбцов по строкам или оси = 1. В этом конкретном примере среднее значение по строкам дает среднее значение или процент оценок, полученных каждым учеником.
В этом руководстве по Pandas мы узнали, как рассчитать среднее значение всего DataFrame, по столбцу (столбцам) и строкам.
Pandas Mean: Calculate Pandas Average for One or Multiple Columns
In this post, you’ll learn how to calculate the Pandas mean (average) for one column, multiple columns, or an entire dataframe. You’ll also learn how to skip na values or include them in your calculation.
Table of Contents
Loading a Sample Dataframe
If you want a sample dataframe to follow along with, load the sample dataframe below. The data represents people’s salaries over a period of four years:
This returns the following dataframe:
Pandas Mean on a Single Column
It’s very easy to calculate a mean for a single column. We can simply call the .mean() method on a single column and it returns the mean of that column.
For example, let’s calculate the average salary Carl had over the years:
We can see here that Carl’s average salary over the four years has been 2150 .
Pandas Mean on a Row
Now, say you wanted to calculate the average for a dataframe row. We can do this by simply modifying the axis= parameter.
Let’s say we wanted to return the average for everyone’s salaries for the year 2018. We can access the 2018 row data by using .loc (which you can learn more about by checking out my tutorial here).
Now, alternatively, you could return the mean for everyone row. You can do this by not including the row selection and modifying the axis= parameter.
Let’s give this a shot:
This returns the following series:
Pandas Average on Multiple Columns
If you wanted to calculate the average of multiple columns, you can simply pass in the .mean() method to multiple columns being selected.
In the example below, we return the average salaries for Carl and Jane. Note that you need to use double square brackets in order to properly select the data:
This returns the following:
Pandas Mean on Entire Dataframe
Finally, if you wanted to return the mean for every column in a Pandas dataframe, you can simply apply the .mean() method to the entire dataframe.
Let’s give this a shot by writing the code below:
Now you’re able to calculate the mean for the entire dataframe.
Include NAs in Calculating Pandas Mean
One important thing to note is that by default, missing values will be excluded from calculating means. It thereby treats a missing value, rather than a 0.
If you wanted to calculate the mean by including missing values, you could first assign values using the Pandas .fillna() method. Check out my tutorial here to learn more:
Let’s calculate the mean with both including and excluding the missing value in Melissa’s column:
Use Pandas Describe to Calculate Means
Finally, let’s use the Pandas .describe() method to calculate the mean (as well as some other helpful statistics). To learn more about the Pandas .describe() method, check out my tutorial here.
Let’s see how we can get the mean and some other helpful statistics:
If you only wanted to return the mean, you could simply use the .loc accessor to access the data:
Conclusion
In this post, you learned how to calculate the Pandas mean, using the .mean() method. You learned how to calculate a mean based on a column, a row, multiple columns, and the entire dataframe. Additionally, you learned how to calculate the mean by including missing values.
To learn more about the Pandas .mean() method, check out the official documentation here.
pandas get column average/mean
![]()
If you only want the mean of the weight column, select the column (which is a Series) and call .mean() :
![]()
![]()
Try df.mean(axis=0) , axis=0 argument calculates the column wise mean of the dataframe so the result will be axis=1 is row wise mean so you are getting multiple values.
Do try to give print (df.describe()) a shot. I hope it will be very helpful to get an overall description of your dataframe.
![]()
Mean for each column in df :
and if you want average of all columns:
![]()
you will get basic statistics of the dataframe and to get mean of specific column you can use
![]()
You can also access a column using the dot notation (also called attribute access) and then calculate its mean:
![]()
You can use either of the two statements below:
![]()
![]()
Additionally if you want to get the round value after finding the mean .
![]()
You can simply go for: df.describe() that will provide you with all the relevant details you need, but to find the min, max or average value of a particular column (say ‘weights’ in your case), use:
Do note that it needs to be in the numeric data type in the first place.
Next find the mean on one column or for all numeric columns using describe() .
Example of result from describe:
You can use the method agg ( aggregate ):
It’s possible to apply multiple statistics:
![]()
You can easily follow the following code
![]()
![]()
-
The Overflow Blog
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.11.43304
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.