- GroupBy#
- Indexing, iteration#
- Function application helper#
- Function application#
- DataFrameGroupBy computations / descriptive stats#
- SeriesGroupBy computations / descriptive stats#
- Plotting and visualization#
- pandas.core.groupby.DataFrameGroupBy.get_group#
- Понимание функции Pandas groupby()
- Что такое функция groupby()?
- groupby() с несколькими столбцами
- Для просмотра групп
- Выбор группы
GroupBy#
GroupBy objects are returned by groupby calls: pandas.DataFrame.groupby() , pandas.Series.groupby() , etc.
Indexing, iteration#
Construct DataFrame from group with provided name.
Construct DataFrame from group with provided name.
A Grouper allows the user to specify a groupby instruction for an object.
Function application helper#
Helper for column specific aggregation with control over output column names.
Function application#
Apply function func group-wise and combine the results together.
Apply function func group-wise and combine the results together.
Aggregate using one or more operations over the specified axis.
Aggregate using one or more operations over the specified axis.
Aggregate using one or more operations over the specified axis.
Aggregate using one or more operations over the specified axis.
Call function producing a same-indexed Series on each group.
Call function producing a same-indexed DataFrame on each group.
Apply a func with arguments to this GroupBy object and return its result.
Apply a func with arguments to this GroupBy object and return its result.
Filter elements from groups that don’t satisfy a criterion.
Filter elements from groups that don’t satisfy a criterion.
DataFrameGroupBy computations / descriptive stats#
Return True if all values in the group are truthful, else False.
Return True if any value in the group is truthful, else False.
Compute pairwise correlation of columns, excluding NA/null values.
Compute pairwise correlation.
Compute count of group, excluding missing values.
Compute pairwise covariance of columns, excluding NA/null values.
Number each item in each group from 0 to the length of that group — 1.
Cumulative max for each group.
Cumulative min for each group.
Cumulative product for each group.
Cumulative sum for each group.
Generate descriptive statistics.
First discrete difference of element.
Fill NA/NaN values using the specified method within groups.
Compute the first non-null entry of each column.
Return first n rows of each group.
Return index of first occurrence of maximum over requested axis.
Return index of first occurrence of minimum over requested axis.
Compute the last non-null entry of each column.
Compute max of group values.
Compute mean of groups, excluding missing values.
Compute median of groups, excluding missing values.
Compute min of group values.
Number each group from 0 to the number of groups — 1.
Take the nth row from each group if n is an int, otherwise a subset of rows.
Return DataFrame with counts of unique elements in each position.
Compute open, high, low and close values of a group, excluding missing values.
Calculate pct_change of each value to previous entry in group.
Compute prod of group values.
Return group values at the given quantile, a la numpy.percentile.
Provide the rank of values within each group.
Provide resampling when using a TimeGrouper.
Return a rolling grouper, providing rolling functionality per group.
Return a random sample of items from each group.
Compute standard error of the mean of groups, excluding missing values.
Shift each group by periods observations.
Return unbiased skew within groups.
Compute standard deviation of groups, excluding missing values.
Compute sum of group values.
Compute variance of groups, excluding missing values.
Return last n rows of each group.
Return the elements in the given positional indices in each group.
Return a Series or DataFrame containing counts of unique rows.
SeriesGroupBy computations / descriptive stats#
Return True if all values in the group are truthful, else False.
Return True if any value in the group is truthful, else False.
Compute correlation with other Series, excluding missing values.
Compute count of group, excluding missing values.
Compute covariance with Series, excluding missing values.
Number each item in each group from 0 to the length of that group — 1.
Cumulative max for each group.
Cumulative min for each group.
Cumulative product for each group.
Cumulative sum for each group.
Generate descriptive statistics.
First discrete difference of element.
Fill NA/NaN values using the specified method within groups.
Compute the first non-null entry of each column.
Return first n rows of each group.
Compute the last non-null entry of each column.
Return the row label of the maximum value.
Return the row label of the minimum value.
Return boolean if values in the object are monotonically increasing.
Return boolean if values in the object are monotonically decreasing.
Compute max of group values.
Compute mean of groups, excluding missing values.
Compute median of groups, excluding missing values.
Compute min of group values.
Number each group from 0 to the number of groups — 1.
Return the largest n elements.
Return the smallest n elements.
Take the nth row from each group if n is an int, otherwise a subset of rows.
Return number of unique elements in the group.
Return unique values of Series object.
Compute open, high, low and close values of a group, excluding missing values.
Calculate pct_change of each value to previous entry in group.
Compute prod of group values.
Return group values at the given quantile, a la numpy.percentile.
Provide the rank of values within each group.
Provide resampling when using a TimeGrouper.
Return a rolling grouper, providing rolling functionality per group.
Return a random sample of items from each group.
Compute standard error of the mean of groups, excluding missing values.
Shift each group by periods observations.
Return unbiased skew within groups.
Compute standard deviation of groups, excluding missing values.
Compute sum of group values.
Compute variance of groups, excluding missing values.
Return last n rows of each group.
Return the elements in the given positional indices in each group.
Plotting and visualization#
Make box plots from DataFrameGroupBy data.
Make a histogram of the DataFrame’s columns.
Draw histogram of the input series using matplotlib.
Make plots of Series or DataFrame.
Make plots of Series or DataFrame.
pandas.core.groupby.DataFrameGroupBy.get_group#
The DataFrame to take the DataFrame out of. If it is None, the object groupby was called on will be used.
Deprecated since version 2.1.0: The obj is deprecated and will be removed in a future version. Do df.iloc[gb.indices.get(name)] instead of gb.get_group(name, obj=df) .
>>> lst = ['a', 'a', 'b'] >>> ser = pd.Series([1, 2, 3], index=lst) >>> ser a 1 a 2 b 3 dtype: int64 >>> ser.groupby(level=0).get_group("a") a 1 a 2 dtype: int64
>>> data = [[1, 2, 3], [1, 5, 6], [7, 8, 9]] >>> df = pd.DataFrame(data, columns=["a", "b", "c"], . index=["owl", "toucan", "eagle"]) >>> df a b c owl 1 2 3 toucan 1 5 6 eagle 7 8 9 >>> df.groupby(by=["a"]).get_group(1) a b c owl 1 2 3 toucan 1 5 6
>>> ser = pd.Series([1, 2, 3, 4], index=pd.DatetimeIndex( . ['2023-01-01', '2023-01-15', '2023-02-01', '2023-02-15'])) >>> ser 2023-01-01 1 2023-01-15 2 2023-02-01 3 2023-02-15 4 dtype: int64 >>> ser.resample('MS').get_group('2023-01-01') 2023-01-01 1 2023-01-15 2 dtype: int64
Понимание функции Pandas groupby()
В этой статье мы поймем работу функции Pandas groupby() на различных примерах.
Что такое функция groupby()?
Модуль Python Pandas широко используется для улучшения предварительной обработки данных и используется для визуализации данных.
Модуль Pandas имеет различные встроенные функции для более эффективной работы с данными. Функция dataframe.groupby() function используется для разделения и выделения некоторой части данных из всего набора данных на основе определенных предопределенных условий или параметров.
dataframe.groupby('column-name')
Используя приведенный выше синтаксис, мы можем разделить набор данных и выбрать все данные, принадлежащие переданному столбцу, в качестве аргумента функции.
import pandas data = pandas.read_csv("C:/marketing_tr.csv") data_grp = data.groupby('marital') data_grp.first()
В приведенном выше примере мы использовали функцию groupby() для разделения и отдельного создания нового фрейма данных со всеми данными, принадлежащими столбцу marital, соответственно.
groupby() с несколькими столбцами
Разделение данных по нескольким значениям столбца можно выполнить с помощью функции Pandas dataframe.groupby() function . Таким образом, мы можем передать несколько тегов столбцов в качестве аргументов для разделения и разделения значений данных вместе со значениями только этих столбцов.
dataframe.groupby(['column1', 'column2', . 'columnN'])
import pandas data = pandas.read_csv("C:/marketing_tr.csv")4 data_grp = data.groupby(['marital','schooling']) data_grp.first()
Для просмотра групп
Помимо разделения данных в соответствии с определенным значением столбца, мы можем даже просмотреть детали каждой группы, сформированной из категорий столбца, используя функцию dataframe.groupby().groups .
Вот снимок образца набора данных, используемого в этом примере:
dataframe.groupby('column').groups
import pandas data = pandas.read_csv("C:/marketing_tr.csv") data_grp = data.groupby('marital').groups data_grp
Как видно выше, мы разделили данные и сформировали новый фрейм данных значений из столбца — «семейный».
Кроме того, мы использовали функцию groupby(). Groups для отображения всех категорий значений, присутствующих в этом конкретном столбце.
Кроме того, он также представляет положение этих категорий в исходном наборе данных вместе с типом данных и количеством имеющихся значений.
Выбор группы
Как мы видели до сих пор, мы можем просматривать различные категории обзора уникальных значений, представленных в столбце с его деталями.
Используя dataframe.get_group(‘column-value’) , мы можем отображать значения, принадлежащие определенной категории / значению данных столбца, сгруппированного функцией groupby().
dataframe.get_group('column-value')
import pandas data = pandas.read_csv("C:/marketing_tr.csv") data_grp = data.groupby('marital') df = data_grp.get_group('divorced') df.head()
В приведенном выше примере мы отобразили данные, принадлежащие значению столбца «divorced» столбца «marital».