Python pandas groupby среднее значение

Как вычислить среднее по данным, группированным по нескольким столбцам в pandas?

В дополнение к этому использовал duplicated, чтобы не учитывать количества при поиске дубликатов. Получилось так:

tpep_pickup_date tpep_pickup_hour region passenger_count count
5 2016-06-01 0 1075 2 4
6 2016-06-01 0 1075 5 1
8 2016-06-01 0 1076 2 3
9 2016-06-01 0 1076 3 2
10 2016-06-01 0 1076 6 2

На первый взгляд, лучше, но проблему это не решило.

2)groupby(. ).sum() просто даёт пустой dataframe.

3) Пробовал делать три вложенных цикла (по дням, часам и регионам), прямо выбирать из них нужное и считать функционал:

1 2 3 4 5 6 7 8 9 10 11 12 13 14
grouped = data.groupby(['tpep_pickup_date', 'tpep_pickup_hour', 'region','passenger_count'], sort=True).size().reset_index(name="count") dates = grouped['tpep_pickup_date'].value_counts().index hours = grouped['tpep_pickup_hour'].value_counts().index regions = grouped['region'].value_counts().index for i in range(len(dates)): for j in range(len(hours)): for k in range(len(regions)): current = grouped[(grouped['region'] == regions[k]) \ & (grouped['tpep_pickup_date'] == dates[i]) & (grouped['tpep_pickup_hour'] == hours[j])] if len(current) > 0: s = sum(current['passenger_count']*current['count'])/sum(current['count']) for index in current.index: grouped.loc[index,'passenger_count'] = s

Этот вариант делает то, что мне нужно. Но работает ужасно медленно (где-то 30 часов). Я уверен, что в Питоне должен быть более производительный и короткий способ провернуть подобное.

Источник

Читайте также:  Таблицы

Mean Value in Each Group in Pandas Groupby

You can use Pandas groupby to group the underlying data on one or more columns and estimate useful statistics like count, sum, mean, median, min, max, etc. In this tutorial, we will look at how to get the mean for each group in pandas groupby with the help of some examples.

If you prefer video over text, check out the following video detailing the steps in this tutorial –

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Mean of each group in pandas groupby

Pandas Groupby Mean

To get the average (or mean) value of in each group, you can directly apply the pandas mean() function to the selected columns from the result of pandas groupby. The following is a step-by-step guide of what you need to do.

  1. Group the dataframe on the column(s) you want.
  2. Select the field(s) for which you want to estimate the mean.
  3. Apply the pandas mean() function directly or pass ‘mean’ to the agg() function.

The following is the syntax –

# groupby columns Col1 and estimate the mean of column Col2 df.groupby([Col1])[Col2].mean() # alternatively, you can pass 'mean' to the agg() function df.groupby([Col1])[Col2].agg('mean')

Examples

Let’s now look at some examples of using the above syntax to get the average values for each group. First, we will create a sample dataframe that we will be using throughout this tutorial.

import pandas as pd # create a dataframe of car models by two companies df = pd.DataFrame(< 'Name': ['Rob', 'Rob', 'Rob', 'Emma', 'Emma', 'Emma', 'Hasan', 'Hasan', 'Hasan'], 'Subject': ['English', 'Science', 'Maths', 'English', 'Science', 'Maths', 'English', 'Science', 'Maths'], 'Marks': [67, 81, 59, 91, 80, 82, 73, 76, 54], 'Projects': [0, 1, 0, 1, 1, 0, 0, 2, 0] >) # display the dataframe df

Dataframe containing the marks and project submission data of three students in different subjects.

Here we created a dataframe storing the marks obtained by some students in a high school in different subjects. The “Projects” field tells the number of projects submitted by the student in that subject.

Groupby Mean of a Single Column

Let’s get the average marks obtained by each student across all the subjects in the above dataframe. For this, we need to group the dataframe on “Name” and then estimate the mean of the “Marks” column.

# average marks for each student df.groupby('Name')['Marks'].mean()
Name Emma 84.333333 Hasan 67.666667 Rob 69.000000 Name: Marks, dtype: float64

You can see that we get the average marks for each student considering all the subjects. “Emma” has the highest average among the three students.

Alternatively, you can also use the agg() function with “mean” as the argument to get the mean of each group in pandas groupby.

# average marks for each student df.groupby('Name')['Marks'].agg('mean')
Name Emma 84.333333 Hasan 67.666667 Rob 69.000000 Name: Marks, dtype: float64

We get the same result as above.

Groupby Mean of Multiple Columns

You can also get the mean of multiple columns at a time for each group. For example, let’s get the average number of projects submissions for each student along with their average marks.

# mean marks and project submissions for each student df.groupby('Name')[['Marks', 'Projects']].mean()

Mean value of

Here, we grouped the data on the “Name” column and then calculated the mean of values in the columns “Marks” and “Projects” for each group.

Alternatively, we can use the agg() function with “mean” as the argument.

# mean marks and project submissions for each student df.groupby('Name')[['Marks', 'Projects']].agg('mean')

Mean value of

We get the same result as above.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Pandas: как группировать и агрегировать по нескольким столбцам

Часто вам может понадобиться группировать и агрегировать по нескольким столбцам кадра данных pandas.

К счастью, это легко сделать с помощью функций pandas .groupby() и .agg() .

В этом руководстве объясняется несколько примеров использования этих функций на практике.

Пример 1: группировка по двум столбцам и поиск среднего

Предположим, у нас есть следующие Pandas DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame print(df) team position assists rebounds 0 A G 5 11 1 B G 7 8 2 B F 7 10 3 B G 8 6 4 B F 5 6 5 M F 7 9 6 M C 6 6 7 M C 9 10 

Следующий код показывает, как сгруппировать по столбцам «команда» и «позиция» и найти средние передачи:

df.groupby(['team', 'position']).agg(). reset_index() team position assists mean 0 A G 5.0 1 B F 6.0 2 B G 7.5 3 M C 7.5 4 M F 7.0 
  • Среднее количество передач для игроков на позиции G в команде А равно 5,0 .
  • Среднее количество передач для игроков на позиции F в команде B равно 6,0 .
  • Среднее количество передач для игроков на позиции G в команде B равно 7,5 .

Мы также можем использовать следующий код для переименования столбцов в результирующем DataFrame:

#group by team and position and find mean assists new = df.groupby(['team', 'position']).agg(). reset_index() #rename columns new.columns = ['team', 'pos', 'mean_assists'] #view DataFrame print(new) team pos mean_assists 0 A G 5.0 1 B F 6.0 2 B G 7.5 3 M C 7.5 4 M F 7.0 

Пример 2: группировка по двум столбцам и поиск нескольких статистических данных

Предположим, мы используем тот же DataFrame pandas, что и в предыдущем примере:

import pandas as pd #create DataFrame df = pd.DataFrame() 

Следующий код показывает, как найти медиану и максимальное количество подборов, сгруппированных по столбцам «команда» и «позиция»:

df.groupby(['team', 'position']).agg(). reset_index() team position rebounds median max 0 A G 11 11 1 B F 8 10 2 B G 7 8 3 M C 8 10 4 M F 9 9 
  • Среднее количество передач по подборам для игроков на позиции G в команде А равно 11 .
  • Максимальное количество подборов для игроков на позиции G в команде A равно 11 .
  • Среднее количество подборов для игроков на позиции F в команде B равно 8 .
  • Максимальное количество подборов для игроков на позиции F в команде B равно 10 .

Источник

Оцените статью