Метод group by python

Понимание функции Pandas groupby()

В этой статье мы поймем работу функции 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, соответственно.

Python Pandas groupby() function

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 для отображения всех категорий значений, присутствующих в этом конкретном столбце.

Кроме того, он также представляет положение этих категорий в исходном наборе данных вместе с типом данных и количеством имеющихся значений.

Читайте также:  What is препроцессор css

Выбор группы

Как мы видели до сих пор, мы можем просматривать различные категории обзора уникальных значений, представленных в столбце с его деталями.

Используя 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».

Источник

pandas.DataFrame.groupby#

Group DataFrame using a mapper or by a Series of columns.

A groupby operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups.

Parameters by mapping, function, label, pd.Grouper or list of such

Used to determine the groups for the groupby. If by is a function, it’s called on each value of the object’s index. If a dict or Series is passed, the Series or dict VALUES will be used to determine the groups (the Series’ values are first aligned; see .align() method). If a list or ndarray of length equal to the selected axis is passed (see the groupby user guide), the values are used as-is to determine the groups. A label or list of labels may be passed to group by the columns in self . Notice that a tuple is interpreted as a (single) key.

Split along rows (0) or columns (1). For Series this parameter is unused and defaults to 0.

level int, level name, or sequence of such, default None

If the axis is a MultiIndex (hierarchical), group by a particular level or levels. Do not specify both by and level .

as_index bool, default True

For aggregated output, return object with group labels as the index. Only relevant for DataFrame input. as_index=False is effectively “SQL-style” grouped output.

Читайте также:  Set env java home

sort bool, default True

Sort group keys. Get better performance by turning this off. Note this does not influence the order of observations within each group. Groupby preserves the order of rows within each group.

Changed in version 2.0.0: Specifying sort=False with an ordered categorical grouper will no longer sort the values.

When calling apply and the by argument produces a like-indexed (i.e. a transform ) result, add group keys to index to identify pieces. By default group keys are not included when the result’s index (and column) labels match the inputs, and are included otherwise.

Changed in version 1.5.0: Warns that group_keys will no longer be ignored when the result from apply is a like-indexed Series or DataFrame. Specify group_keys explicitly to include the group keys or not.

Changed in version 2.0.0: group_keys now defaults to True .

This only applies if any of the groupers are Categoricals. If True: only show observed values for categorical groupers. If False: show all values for categorical groupers.

dropna bool, default True

If True, and if group keys contain NA values, NA values together with row/column will be dropped. If False, NA values will also be treated as the key in groups.

Returns a groupby object that contains information about the groups.

Convenience method for frequency conversion and resampling of time series.

See the user guide for more detailed usage and examples, including splitting an object into groups, iterating through groups, selecting a group, aggregation, and more.

>>> df = pd.DataFrame('Animal': ['Falcon', 'Falcon', . 'Parrot', 'Parrot'], . 'Max Speed': [380., 370., 24., 26.]>) >>> df Animal Max Speed 0 Falcon 380.0 1 Falcon 370.0 2 Parrot 24.0 3 Parrot 26.0 >>> df.groupby(['Animal']).mean() Max Speed Animal Falcon 375.0 Parrot 25.0 

Hierarchical Indexes

We can groupby different levels of a hierarchical index using the level parameter:

>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'], . ['Captive', 'Wild', 'Captive', 'Wild']] >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type')) >>> df = pd.DataFrame('Max Speed': [390., 350., 30., 20.]>, . index=index) >>> df Max Speed Animal Type Falcon Captive 390.0 Wild 350.0 Parrot Captive 30.0 Wild 20.0 >>> df.groupby(level=0).mean() Max Speed Animal Falcon 370.0 Parrot 25.0 >>> df.groupby(level="Type").mean() Max Speed Type Captive 210.0 Wild 185.0 

We can also choose to include NA in group keys or not by setting dropna parameter, the default setting is True .

>>> l = [[1, 2, 3], [1, None, 4], [2, 1, 3], [1, 2, 2]] >>> df = pd.DataFrame(l, columns=["a", "b", "c"]) 
>>> df.groupby(by=["b"]).sum() a c b 1.0 2 3 2.0 2 5 
>>> df.groupby(by=["b"], dropna=False).sum() a c b 1.0 2 3 2.0 2 5 NaN 1 4 
>>> l = [["a", 12, 12], [None, 12.3, 33.], ["b", 12.3, 123], ["a", 1, 1]] >>> df = pd.DataFrame(l, columns=["a", "b", "c"]) 
>>> df.groupby(by="a").sum() b c a a 13.0 13.0 b 12.3 123.0 
>>> df.groupby(by="a", dropna=False).sum() b c a a 13.0 13.0 b 12.3 123.0 NaN 12.3 33.0 

When using .apply() , use group_keys to include or exclude the group keys. The group_keys argument defaults to True (include).

>>> df = pd.DataFrame('Animal': ['Falcon', 'Falcon', . 'Parrot', 'Parrot'], . 'Max Speed': [380., 370., 24., 26.]>) >>> df.groupby("Animal", group_keys=True).apply(lambda x: x) Animal Max Speed Animal Falcon 0 Falcon 380.0 1 Falcon 370.0 Parrot 2 Parrot 24.0 3 Parrot 26.0 
>>> df.groupby("Animal", group_keys=False).apply(lambda x: x) Animal Max Speed 0 Falcon 380.0 1 Falcon 370.0 2 Parrot 24.0 3 Parrot 26.0 

Источник

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