Меню

Ошибки вычисления среднего значения pandas

  • Редакция Кодкампа

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

I’m trying to implement some machine learning algorithms, but I’m having some difficulties putting the data together.

In the example below, I load a example data-set from UCI, remove lines with missing data (thanks to the help from a previous question), and now I would like to try to normalize the data.

For many datasets, I just used:

valores = (valores - valores.mean()) / (valores.std())

But for this particular dataset the approach above doesn’t work. The problem is that the mean function is returning inf, perhaps due to a precision issue. See the example below:

bcw = pd.read_csv('http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', header=None)

for col in bcw.columns:
    if bcw[col].dtype != 'int64':
        print "Removendo possivel '?' na coluna %s..." % col
        bcw = bcw[bcw[col] != '?']

valores = bcw.iloc[:,1:10]
#mean return inf
print  valores.iloc[:,5].mean()

My question is how to deal with this. It seems that I need to change the type of this column, but I don’t know how to do it.

Errorbar is the plotted chart that refers to the errors contained in the data frame, which shows the confidence & precision in a set of measurements or calculated values. Error bars help in showing the actual and exact missing parts as well as visually display the errors in different areas in the data frame. Error bars are the descriptive behavior that holds information about the variances in data as well as advice to make proper changes to build data more insightful and impactful for the users.

Here we discuss how we plot errorbar with mean and standard deviation after grouping up the data frame with certain applied conditions such that errors become more truthful to make necessary for obtaining the best results and visualizations. 

Modules Needed:

pip install numpy
pip install pandas
pip install matplotlib

Here is the DataFrame from which we illustrate the errorbars with mean and std: 
 

Python3

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

df = pd.DataFrame({

    'insert': [0.0, 0.1, 0.3, 0.5, 1.0],

    'mean': [0.009905, 0.45019, 0.376818, 0.801856, 0.643859],

    'quality': ['good', 'good', 'poor', 'good', 'poor'],

    'std': [0.003662, 0.281895, 0.306806, 0.243288, 0.322378]})

print(df)

Output:

Sample DataFrame

groupby the subplots with mean and std to get error bars: 

Python3

fig, ax = plt.subplots()

for key, group in df.groupby('quality'):

    group.plot('insert', 'mean', yerr='std',

               label=key, ax=ax)

plt.show()

 
 Output:

Example 1: ErrorBar with group-plot

Now we see error bars using NumPy keywords of mean and std:

Python3

qual = df.groupby("quality").agg([np.mean, np.std])

qual = qual['insert']

qual.plot(kind = "barh", y = "mean", legend = False,

          xerr = "std", title = "Quality", color='green')

 
 Output:

Example 2: ErrorBar with Bar Plot

By the above example, we can see that errors in poor quality are higher than good instead of more good values in the data frame.

Now, we move with another example with data frame below:

Dataset – Toast

 By the above data frame, we have to manipulate this data frame to get the errorbars by using the ‘type’ column having different prices of the bags. To manipulation and perform calculations, we have to use a df.groupby function that has a prototype to check the field and execute the function to evaluate result.

We are using two inbuilt functions of mean and std: 

df.groupby("col_to_group_by").agg([func_1, func_2, func_3, .....])

Python3

df = pd.read_csv('Toast.csv')

df_prices = df.groupby("type").agg([np.mean, np.std])

As we have to evaluate the average price, so apply this groupby on ‘AveragePrice’. Also, check the result of prices and with the visualization display the errorbars

Python3

prices = df_prices['AveragePrice']

prices.head()

 
 Output:

Result: the aggregate value of  groupby()

Errorbar using Mean:

Python3

prices.plot(kind = "barh", y = "mean", legend = False,

            title = "Average Prices")

 
 Output:

Example 3: Errorbar with Mean

By the above visualization, it’s clear that organic has a higher mean price than conventional.

Errorbar using Standard Deviation (std):

Python3

prices.plot(kind = "barh", y = "mean", legend = False,

            title = "Average Prices", xerr = "std")

Output:

Example 4: Errorbar with Std

Advantages of Errorbars:

  • Errorbars are more obstacles.
  • They are easy to execute with good estimation values.
  • Relatively uniform because of complex interpretation power with a data frame.

Errorbar is the plotted chart that refers to the errors contained in the data frame, which shows the confidence & precision in a set of measurements or calculated values. Error bars help in showing the actual and exact missing parts as well as visually display the errors in different areas in the data frame. Error bars are the descriptive behavior that holds information about the variances in data as well as advice to make proper changes to build data more insightful and impactful for the users.

Here we discuss how we plot errorbar with mean and standard deviation after grouping up the data frame with certain applied conditions such that errors become more truthful to make necessary for obtaining the best results and visualizations. 

Modules Needed:

pip install numpy
pip install pandas
pip install matplotlib

Here is the DataFrame from which we illustrate the errorbars with mean and std: 
 

Python3

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

df = pd.DataFrame({

    'insert': [0.0, 0.1, 0.3, 0.5, 1.0],

    'mean': [0.009905, 0.45019, 0.376818, 0.801856, 0.643859],

    'quality': ['good', 'good', 'poor', 'good', 'poor'],

    'std': [0.003662, 0.281895, 0.306806, 0.243288, 0.322378]})

print(df)

Output:

Sample DataFrame

groupby the subplots with mean and std to get error bars: 

Python3

fig, ax = plt.subplots()

for key, group in df.groupby('quality'):

    group.plot('insert', 'mean', yerr='std',

               label=key, ax=ax)

plt.show()

 
 Output:

Example 1: ErrorBar with group-plot

Now we see error bars using NumPy keywords of mean and std:

Python3

qual = df.groupby("quality").agg([np.mean, np.std])

qual = qual['insert']

qual.plot(kind = "barh", y = "mean", legend = False,

          xerr = "std", title = "Quality", color='green')

 
 Output:

Example 2: ErrorBar with Bar Plot

By the above example, we can see that errors in poor quality are higher than good instead of more good values in the data frame.

Now, we move with another example with data frame below:

Dataset – Toast

 By the above data frame, we have to manipulate this data frame to get the errorbars by using the ‘type’ column having different prices of the bags. To manipulation and perform calculations, we have to use a df.groupby function that has a prototype to check the field and execute the function to evaluate result.

We are using two inbuilt functions of mean and std: 

df.groupby("col_to_group_by").agg([func_1, func_2, func_3, .....])

Python3

df = pd.read_csv('Toast.csv')

df_prices = df.groupby("type").agg([np.mean, np.std])

As we have to evaluate the average price, so apply this groupby on ‘AveragePrice’. Also, check the result of prices and with the visualization display the errorbars

Python3

prices = df_prices['AveragePrice']

prices.head()

 
 Output:

Result: the aggregate value of  groupby()

Errorbar using Mean:

Python3

prices.plot(kind = "barh", y = "mean", legend = False,

            title = "Average Prices")

 
 Output:

Example 3: Errorbar with Mean

By the above visualization, it’s clear that organic has a higher mean price than conventional.

Errorbar using Standard Deviation (std):

Python3

prices.plot(kind = "barh", y = "mean", legend = False,

            title = "Average Prices", xerr = "std")

Output:

Example 4: Errorbar with Std

Advantages of Errorbars:

  • Errorbars are more obstacles.
  • They are easy to execute with good estimation values.
  • Relatively uniform because of complex interpretation power with a data frame.

  • Чтобы вычислить среднее значение в Pandas DataFrame, вы можете использовать метод pandas.DataFrame.mean(). Используя метод mean(), вы можете вычислить среднее значение по оси или по всему DataFrame.

Пример 1

В этом примере мы рассчитаем среднее значение по столбцам. Мы узнаем средние оценки, полученные студентами по предметам.

import pandas as pd

mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

# create dataframe
df_marks = pd.DataFrame(mydictionary)
print('DataFramen----------')
print(df_marks)

# calculate mean
mean = df_marks.mean()
print('nMeann------')
print(mean)

Вывод:

DataFrame
----------
  names  physics  chemistry  algebra
0  Somu       68         84       78
1  Kiku       74         56       88
2  Amol       77         73       82
3  Lini       78         69       87

Mean
------
physics      74.25
chemistry    70.50
algebra      83.75
dtype: float64

Функция mean() возвращает Pandas, это поведение функции mean() по умолчанию. Следовательно, в этом конкретном случае вам не нужно передавать какие-либо аргументы функции mean(). Или, если вы хотите явно указать функцию для вычисления по столбцам, передайте axis = 0, как показано ниже.

df_marks.mean(axis=0)

Пример 2

В этом примере мы создадим DataFrame с числами, присутствующими во всех столбцах, и вычислим среднее значение.

Из предыдущего примера мы видели, что функция mean() по умолчанию возвращает среднее значение, вычисленное среди столбцов.

import pandas as pd

mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

# create dataframe
df_marks = pd.DataFrame(mydictionary)
print('DataFramen----------')
print(df_marks)

# calculate mean of the whole DataFrame
mean = df_marks.mean().mean()
print('nMeann------')
print(mean)

Вывод:

DataFrame
----------
  names  physics  chemistry  algebra
0  Somu       68         84       78
1  Kiku       74         56       88
2  Amol       77         73       82
3  Lini       78         69       87

Mean
------
76.16666666666667

Пример 3: по строкам

В этом примере мы вычислим среднее значение всех столбцов по строкам или оси = 1. В этом конкретном примере среднее значение по строкам дает среднее значение или процент оценок, полученных каждым учеником.

import pandas as pd

mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],
	'physics': [68, 74, 77, 78],
	'chemistry': [84, 56, 73, 69],
	'algebra': [78, 88, 82, 87]}

# create dataframe
df_marks = pd.DataFrame(mydictionary)
print('DataFramen----------')
print(df_marks)

# calculate mean along rows
mean = df_marks.mean(axis=1)
print('nMeann------')
print(mean)

# display names and average marks
print('nAverage marks or percentage for each student')
print(pd.concat([df_marks['names'], mean], axis=1))

Вывод:

DataFrame
----------
  names  physics  chemistry  algebra
0  Somu       68         84       78
1  Kiku       74         56       88
2  Amol       77         73       82
3  Lini       78         69       87

Mean
------
0    76.666667
1    72.666667
2    77.333333
3    78.000000
dtype: float64

Average marks or percentage for each student
  names          0
0  Somu  76.666667
1  Kiku  72.666667
2  Amol  77.333333
3  Lini  78.000000

В этом руководстве по Pandas мы узнали, как рассчитать среднее значение всего DataFrame, по столбцу (столбцам) и строкам.

This div height required for enabling the sticky sidebar

Среднее – это значение, представляющее весь набор объектов. Считается центральным значением набора чисел.

Среднее значение рассчитывается путем деления суммы всех значений объектов на количество объектов.

Формула: (сумма значений) / общие значения

Теперь давайте разберемся, как работает функция mean() для вычисления среднего значения.

Содержание

  1. Использование функции mean()
  2. mean() с модулем NumPy
  3. Функция mean() с модулем Pandas

Функция mean() помогает вычислить среднее значение набора значений, переданных в функцию.

Модуль статистики в Python используется для выполнения всех статистических операций с данными. Нам нужно импортировать модуль статистики, используя следующую команду:

Синтаксис:

import statistics

Функция statistics.mean() принимает значения данных в качестве аргумента и возвращает среднее значение переданных ей значений.

Синтаксис:

statistics.mean(data)

Пример:

import statistics
data = [10,20,30,40,50]

res_mean = statistics.mean(data)
print(res_mean)

Вывод:

30

mean() с модулем NumPy

Модуль Python NumPy представляет набор значений в виде массива. Мы можем вычислить среднее значение этих элементов массива с помощью функции numpy.mean().

Функция numpy.mean() работает так же, как функция statistics.mean().

Синтаксис:

numpy.mean(data)

Пример:

import numpy as np
data = np.arange(1,10)
res_mean = np.mean(data)
print(res_mean)

В приведенном выше примере мы использовали функцию numpy.arange (start, stop) для создания равномерно распределенных значений в диапазоне, указанном в качестве параметров. Кроме того, функция numpy.mean() используется для вычисления среднего значения всех элементов массива.

Вывод:

5.0

Функция mean() с модулем Pandas

Модуль Pandas работает с огромными наборами данных в виде DataFrames. Среднее значение этих огромных наборов данных можно вычислить с помощью функции pandas.DataFrame.mean().

Функция pandas.DataFrame.mean() возвращает среднее значение этих значений данных.

Синтаксис:

pandas.DataFrame.mean()

Пример 1:

import numpy as np
import pandas as pd
data = np.arange(1,10)
df = pd.DataFrame(data)
res_mean = df.mean()
print(res_mean)

В приведенном выше примере мы создали массив NumPy с помощью функции numpy.arange(), а затем преобразовали значения массива в DataFrame с помощью функции pandas.DataFrame(). Кроме того, мы вычислили среднее значение значений DataFrame с помощью функции pandas.DataFrame.mean().

Вывод:

0    5.0
dtype: float64

Пример 2:

import pandas as pd 
data = pd.read_csv("C:/mtcars.csv")
res_mean = data['qsec'].mean()
print(res_mean)

Входной набор данных:

Набор данных MTCARS

В приведенном выше примере мы использовали вышеупомянутый набор данных и вычислили среднее значение всех значений данных, представленных в столбце данных «qsec».

Вывод:

17.848750000000003

( 4 оценки, среднее 3.5 из 5 )

Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.

       Y1961      Y1962      Y1963      Y1964      Y1965  Region
0  82.567307  83.104757  83.183700  83.030338  82.831958  US
1   2.699372   2.610110   2.587919   2.696451   2.846247  US
2  14.131355  13.690028  13.599516  13.649176  13.649046  US
3   0.048589   0.046982   0.046583   0.046225   0.051750  US
4   0.553377   0.548123   0.582282   0.577811   0.620999  US

In the above dataframe, I would like to get average of each row. currently, I am doing this:

df.mean(axis=0)

However, this does away with the Region column as well. how can I compute mean and also retain Region column

asked Nov 17, 2015 at 6:15

user308827's user avatar

user308827user308827

20k79 gold badges243 silver badges397 bronze badges

2

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

answered Nov 17, 2015 at 6:31

Alexander's user avatar

AlexanderAlexander

102k28 gold badges196 silver badges191 bronze badges

2

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

answered Oct 1, 2020 at 16:13

KevinCK's user avatar

Taking the mean based on the column names

I am just sharing this which might be useful for those folks who want to take average of a few columns based on the their names, instead of counting the column index. This simply would be done using pandas’s loc instead of iloc. For instance, taking the odd-year average would be:

df["mean_odd_year"] = df.loc[:, ["Y1961","Y1963","Y1965"]].mean(axis = 1)

answered Apr 6, 2022 at 19:31

Pygin's user avatar

PyginPygin

7075 silver badges12 bronze badges

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

answered Nov 12, 2019 at 18:45

pabloverd's user avatar

pabloverdpabloverd

5946 silver badges8 bronze badges

1

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

Balu's user avatar

answered Oct 21, 2016 at 10:12

Rahul's user avatar

RahulRahul

2,0281 gold badge20 silver badges36 bronze badges

1

       Y1961      Y1962      Y1963      Y1964      Y1965  Region
0  82.567307  83.104757  83.183700  83.030338  82.831958  US
1   2.699372   2.610110   2.587919   2.696451   2.846247  US
2  14.131355  13.690028  13.599516  13.649176  13.649046  US
3   0.048589   0.046982   0.046583   0.046225   0.051750  US
4   0.553377   0.548123   0.582282   0.577811   0.620999  US

In the above dataframe, I would like to get average of each row. currently, I am doing this:

df.mean(axis=0)

However, this does away with the Region column as well. how can I compute mean and also retain Region column

asked Nov 17, 2015 at 6:15

user308827's user avatar

user308827user308827

20k79 gold badges243 silver badges397 bronze badges

2

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

answered Nov 17, 2015 at 6:31

Alexander's user avatar

AlexanderAlexander

102k28 gold badges196 silver badges191 bronze badges

2

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

answered Oct 1, 2020 at 16:13

KevinCK's user avatar

Taking the mean based on the column names

I am just sharing this which might be useful for those folks who want to take average of a few columns based on the their names, instead of counting the column index. This simply would be done using pandas’s loc instead of iloc. For instance, taking the odd-year average would be:

df["mean_odd_year"] = df.loc[:, ["Y1961","Y1963","Y1965"]].mean(axis = 1)

answered Apr 6, 2022 at 19:31

Pygin's user avatar

PyginPygin

7075 silver badges12 bronze badges

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

answered Nov 12, 2019 at 18:45

pabloverd's user avatar

pabloverdpabloverd

5946 silver badges8 bronze badges

1

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

Balu's user avatar

answered Oct 21, 2016 at 10:12

Rahul's user avatar

RahulRahul

2,0281 gold badge20 silver badges36 bronze badges

1

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибки выступающих ошибки при подготовке презентации
  • Ошибки вольво фш 13 значки на панели приборов