17 авг. 2022 г.
читать 1 мин
Часто вам может быть интересно вычислить среднее значение одного или нескольких столбцов в кадре данных pandas. К счастью, вы можете легко сделать это в pandas, используя функцию mean() .
В этом руководстве показано несколько примеров использования этой функции.
Пример 1. Найдите среднее значение одного столбца
Предположим, у нас есть следующие Pandas DataFrame:
import pandas as pd
import numpy as np
#create DataFrame
df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'points': [25, 20, 14, 16, 27, 20, 12, 15, 14, 19],
'assists': [5, 7, 7, 8, 5, 7, 6, 9, 9, 5],
'rebounds': [np.nan, 8, 10, 6, 6, 9, 6, 10, 10, 7]})
#view DataFrame
df
player points assists rebounds
0 A 25 5 NaN
1 B 20 7 8.0
2 C 14 7 10.0
3 D 16 8 6.0
4 E 27 5 6.0
5 F 20 7 9.0
6 G 12 6 6.0
7 H 15 9 10.0
8 I 14 9 10.0
9 J 19 5 7.0
Мы можем найти среднее значение столбца под названием «точки», используя следующий синтаксис:
df['points'].mean()
18.2
Функция mean() также будет исключать NA по умолчанию. Например, если мы найдем среднее значение столбца «отскоки», первое значение «NaN» будет просто исключено из расчета:
df['rebounds'].mean()
8.0
Если вы попытаетесь найти среднее значение столбца, который не является числовым, вы получите сообщение об ошибке:
df['player'].mean()
TypeError: Could not convert ABCDEFGHIJ to numeric
Пример 2. Найдите среднее значение нескольких столбцов
Мы можем найти среднее значение нескольких столбцов, используя следующий синтаксис:
#find mean of points and rebounds columns
df[['rebounds', 'points']].mean()
rebounds 8.0
points 18.2
dtype: float64
Пример 3. Найдите среднее значение всех столбцов
Мы можем также найти среднее значение всех числовых столбцов, используя следующий синтаксис:
#find mean of all numeric columns in DataFrame
df.mean ()
points 18.2
assists 6.8
rebounds 8.0
dtype: float64
Обратите внимание, что функция mean() просто пропустит столбцы, которые не являются числовыми.
Дополнительные ресурсы
Как рассчитать медиану в Pandas
Как рассчитать сумму столбцов в Pandas
Как найти максимальное значение столбцов в Pandas
You can easily follow the following code
import pandas as pd
import numpy as np
classxii = {'Name':['Karan','Ishan','Aditya','Anant','Ronit'],
'Subject':['Accounts','Economics','Accounts','Economics','Accounts'],
'Score':[87,64,58,74,87],
'Grade':['A1','B2','C1','B1','A2']}
df = pd.DataFrame(classxii,index = ['a','b','c','d','e'],columns=['Name','Subject','Score','Grade'])
print(df)
#use the below for mean if you already have a dataframe
print('mean of score is:')
print(df[['Score']].mean())
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.
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:
import pandas as pd
df = pd.DataFrame.from_dict(
{
'Year': [2018, 2019, 2020, 2021],
'Carl': [1000, 2300, 1900, 3400],
'Jane': [1500, 1700, 1300, 800],
'Melissa': [800, 2300, None, 2300]
}
).set_index('Year')
print(df)
This returns the following dataframe:
Carl Jane Melissa
Year
2018 1000 1500 800.0
2019 2300 1700 2300.0
2020 1900 1300 NaN
2021 3400 800 2300.0
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:
>>> carl = df['Carl'].mean()
>>> print(carl)
2150.0
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).
YOUTUBE: https://www.youtube.com/watch?v=VIa1ETYnFuc
>>> year_2018 = df.loc[2018,:].mean()
>>> print(year_2018)
1100
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:
row_averages = df.mean(axis=1)
print(row_averages)
This returns the following series:
Year
2018 1100.000000
2019 2100.000000
2020 1600.000000
2021 2166.666667
dtype: float64
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:
averages = df[['Carl', 'Jane']].mean()
print(averages)
This returns the following:
Carl 2150.0
Jane 1325.0
dtype: float64
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:
>>> entire_dataframe = df.mean()
>>> print(entire_dataframe)
Carl 2150.0
Jane 1325.0
Melissa 1800.0
dtype: float64
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:
>>> print(df['Melissa'].mean())
>>> print(df['Melissa'].fillna(0).mean())
1800.0
1350.0
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:
>>> print(df.describe())
Carl Jane Melissa
count 4.000000 4.000000 3.000000
mean 2150.000000 1325.000000 1800.000000
std 994.987437 386.221008 866.025404
min 1000.000000 800.000000 800.000000
25% 1675.000000 1175.000000 1550.000000
50% 2100.000000 1400.000000 2300.000000
75% 2575.000000 1550.000000 2300.000000
max 3400.000000 1700.000000 2300.000000
If you only wanted to return the mean, you could simply use the .loc
accessor to access the data:
>>> print(df.describe().loc['mean'])
Carl 2150.0
Jane 1325.0
Melissa 1800.0
Name: mean, dtype: float64
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.
To get column average or mean from pandas DataFrame use either mean()
and describe()
method. The DataFrame.mean() method is used to return the mean of the values for the requested axis. If you apply this method on a series object, then it returns a scalar value, which is the mean value of all the observations in the pandas DataFrame.
Related: Get all column names from pandas DataFrame
In this article, I will explain how to get column average or mean from pandas DataFrame with examples.
Below are some quick examples of how to get column average or mean in pandas DataFrame.
# Below are quick example
# Using DataFrame.mean() method to get column average
df2 = df["Fee"].mean()
# Using DataFrame.mean() to get entire column mean
df2 = df.mean()
# Using multiple columns mean using DataFrame.mean()
df2 = df[["Fee","Discount"]].mean()
# Average of each column using DataFrame.mean()
df2 = df.mean(axis=0)
# Find the mean including NaN values using DataFrame.mean()
df2 = df.mean(axis = 0, skipna = False)
# Using DataFrame.describe() method
df2 = df.describe()
Now, let’s create a DataFrame with a few rows and columns, execute these examples and validate results. Our DataFrame contains column names Courses
, Fee
, Duration
and Discount
.
import pandas as pd
technologies = {
'Courses':["Spark","PySpark","Python","pandas",None],
'Fee' :[20000,25000,22000,None,30000],
'Duration':['30days','40days','35days','None','50days'],
'Discount':[1000,2300,1200,2000,None]
}
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies,index=index_labels)
print(df)
Yields below output.
Courses Fee Duration Discount
r1 Spark 20000.0 30days 1000.0
r2 PySpark 25000.0 40days 2300.0
r3 Python 22000.0 35days 1200.0
r4 pandas NaN None 2000.0
r5 None 30000.0 50days NaN
2. Get Column Mean
DataFrame.mean() method gets the mean value of a particular column from pandas DataFrame, you can use the df["Fee"].mean()
function for a specific column only.
# Using DataFrame.mean() method to get column average
df2 = df["Fee"].mean()
print(df2)
Yields below output.
24250.0
4. Get Column Mean for All Columns
To calculate the mean of whole columns in the DataFrame, use pandas.Series.mean()
with a list of DataFrame columns. You can also get the mean for all numeric columns using DataFrame.mean(), use axis=0
argument to calculate the column-wise mean of the DataFrame.
# Using DataFrame.mean() to get entire column mean
df2 = df.mean()
print(df2)
# Using multiple columns mean using DataFrame.mean()
df2 = df[["Fee","Discount"]].mean()
print(df2)
# Average of each column using DataFrame.mean()
df2 = df.mean(axis=0)
print(df2)
Above all examples yields the same below output.
Fee 24250.0
Discount 1625.0
dtype: float64
5. Find the Mean Including NaN Values
By default mean() ignores/exclude NaN/null values while calculating mean or average, you can consider these values by using skipna=False
param.
# Find the mean ignoring NaN values using DataFrame.mean()
df2 = df.mean(axis = 0, skipna = False)
print(df2)
I will leave it to you to execute this in your environment.
6. Using DataFrame.describe() Method
You can also use DataFrame.describe()
to create the output of complete statistics of the data in DataFrame.
# Using DataFrame.describe() method
df2 = df.describe()
print(df2)
Yields below output.
Fee Discount
count 4.00000 4.000000
mean 24250.00000 1625.000000
std 4349.32945 623.832242
min 20000.00000 1000.000000
25% 21500.00000 1150.000000
50% 23500.00000 1600.000000
75% 26250.00000 2075.000000
max 30000.00000 2300.000000
7. Complete Example For Get Column Average or Mean
import pandas as pd
technologies = {
'Courses':["Spark","PySpark","Python","pandas",None],
'Fee' :[20000,25000,22000,None,30000],
'Duration':['30days','40days','35days','None','50days'],
'Discount':[1000,2300,1200,2000,None]
}
index_labels=['r1','r2','r3','r4','r5']
df = pd.DataFrame(technologies,index=index_labels)
print(df)
# Using DataFrame.mean() method to get column average
df2 = df["Fee"].mean()
print(df2)
# Using DataFrame.mean() to get entire column mean
df2 = df.mean()
print(df2)
# Using multiple columns mean using DataFrame.mean()
df2 = df[["Fee","Discount"]].mean()
print(df2)
# Average of each column using DataFrame.mean()
df2 = df.mean(axis=0)
print(df2)
# Find the mean ignoring NaN values using DataFrame.mean()
df2 = df.mean(axis = 0, skipna = False)
print(df2)
# Using DataFrame.describe() method
df2 = df.describe()
print(df2)
Conclusion
In this article, you have learned how to get column average or mean from pandas DataFrame using DataFrame.mean() and DataFrame.describe()
method with examples. Using mean() you can get mean from single or selected columns and by index.
Happy Learning !!
Related Articles
- How to Find Installed Pandas Version
- How to Append a List as a Row to Pandas DataFrame
- Pandas Shuffle DataFrame Rows Examples
- Difference Between loc[] vs iloc[] in Pandas
- Retrieve Number of Columns From Pandas DataFrame
- pandas rolling() Mean, Average, Sum Examples
- Count NaN Values in Pandas DataFrame
- Pandas Window Functions Explained
References
- https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mean.html
Время чтения 3 мин.
Функция среднего значения в Pandas используется для вычисления среднего арифметического заданного набора чисел, значения DataFrame, среднего значения столбца или строки или строк в Pandas.
Содержание
- Что такое функция DataFrame.mean() в Pandas?
- Синтаксис
- Параметры
- Возвращаемое значение
- Пример DataFrame.mean()
- Нахождение среднего значения в DataFrame с None
- Поиск среднего значения определенного столбца DataFrame
- Заключение
Чтобы найти среднее значение DataFrame, используйте функцию Pandas DataFrame.mean(). Функция DataFrame.mean() возвращает среднее значение для запрошенной оси.
Если метод mean() применяется к объекту серии Pandas, он возвращает скалярное значение, которое является средним значением всех значений в DataFrame.
Если метод mean() применяется к объекту Pandas DataFrame, он возвращает объект серии pandas, который содержит среднее значение значений по указанной оси.
Синтаксис
DataFrame.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs) |
Параметры
- axis{index (0), columns (1)}
Ось применяемого метода.
- skipna: bool, по умолчанию True.
Исключить значения NA/None при вычислении результата.
- level: int или имя уровня, по умолчанию None.
Если ось представляет собой MultiIndex, считайте вместе с определенным уровнем, сворачиваясь в серию.
- numeric_only: bool, по умолчанию None.
Включать только столбцы типа float, int, boolean. Если значения равны None, будут пытаться использовать все, а затем использовать только числовые данные. Не реализовано для серии.
- **kwargs
Дополнительные аргументы ключевого слова для передачи в функцию.
Возвращаемое значение
Он возвращает Series или DataFrame (если указан уровень).
Пример DataFrame.mean()
В методе df.mean(), если мы не укажем ось, по умолчанию будет использоваться ось индекса.
В приведенном ниже примере мы найдем среднее значение DataFrame относительно оси индекса.
# app.py import pandas as pd data = {‘X’: [29, 46, 10, 36], ‘Y’: [11, 18, 19, 21], ‘Z’: [3, 12, 1, 2]} df = pd.DataFrame.from_dict(data) meanDf = df.mean() print(meanDf) |
Вывод:
X 30.25 Y 17.25 Z 4.50 dtype: float64 |
В этом примере мы получили ряд средних значений относительно оси индекса. Вот так рассчитал:
X = 30,25, это выход 29 + 46 + 10 + 36 = 121. А затем нам нужно разделить его на 4, что дает 30,25. То же самое для Y и Z.
Чтобы вычислить среднее значение по строкам в DataFrame, передайте параметр axis = 1.
# app.py import pandas as pd data = {‘X’: [29, 46, 10, 36], ‘Y’: [11, 18, 19, 21], ‘Z’: [3, 12, 1, 2]} df = pd.DataFrame.from_dict(data) meanDf = df.mean(axis=1) print(meanDf) |
Вывод:
0 14.333333 1 25.333333 2 10.000000 3 19.666667 dtype: float64 |
Здесь внутри функции df.mean() мы передали параметр axis = 1.
Расчет средней функции следующий:
- Для первой строки среднее значение равно 14,33, которое рассчитывается как 29 + 11 + 3 = 43, а затем делится на 3, что дает 14,33. Этот расчет одинаков для второй, третьей и четвертой строк.
- Аргумент df.mean(axis = 0), axis = 0 вычисляет среднее значение по столбцам фрейма данных, так что результатом будет axis = 1, это среднее значение по строке, поэтому вы получаете несколько значений.
Итак, если вы хотите вычислить средние значения по строкам или по столбцам, вам нужно передать соответствующую ось. В противном случае по умолчанию он даст вам среднее значение на основе индекса.
Нахождение среднего значения в DataFrame с None
Бывают случаи, когда вы сталкиваетесь с большим количеством значений None или NaN в DataFrame. Когда мы сталкиваемся с этим, мы можем найти среднее значение по оси столбца.
См. следующий код.
# app.py import pandas as pd data = {‘X’: [29, 46, None, 36], ‘Y’: [11, None, 19, 21], ‘Z’: [3, 12, 1, None]} df = pd.DataFrame.from_dict(data) meanDf = df.mean(axis=1, skipna=True) print(meanDf) |
Вывод:
0 14.333333 1 29.000000 2 10.000000 3 28.500000 dtype: float64 |
Поиск среднего значения определенного столбца DataFrame
Чтобы найти среднее значение определенного столбца DataFrame, используйте df[«column name»].
# app.py import pandas as pd data = {‘X’: [29, 46, None, 36], ‘Y’: [11, None, 19, 21], ‘Z’: [3, 12, 1, None]} df = pd.DataFrame.from_dict(data) meanZ = df[‘Z’].mean() print(meanZ) |
Вывод:
В этом примере мы получили среднее значение столбца Z, который также содержит значения None.
Выход рассчитывается следующим образом: 3 + 12 + 1 = 16, а затем разделите это на 3, что является окончательным выходом = 5,3333.
Заключение
Чтобы вычислить среднее значение Pandas DataFrame, вы можете использовать метод pandas.DataFrame.mean(). Используя метод mean(), вы можете вычислить среднее значение по оси или по всему DataFrame. Просто помните следующие моменты.
- Чтобы найти среднее значение для каждого столбца в DataFrame:
- Чтобы найти среднее значение для каждой строки в DataFrame: