Python pivot table пример

Как создать сводную таблицу Pandas в Python

Сводная таблица Pandas используется для изменения ее формы таким образом, чтобы ее было легче понять или проанализировать. Часто вы будете использовать опорную точку, чтобы продемонстрировать связь между двумя столбцами, о которой может быть трудно рассуждать до опорной точки.

Сводная таблица в Pandas создает сводную таблицу в стиле электронной таблицы как DataFrame в Python. Уровни в сводной таблице будут храниться в объектах MultiIndex (иерархических индексах) в индексе и столбцах результирующего DataFrame.

Возможно, вы знакомы с концепцией сводных таблиц из Excel, где они были зарегистрированы как торговая марка Name PivotTable.

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

Сводная таблица Pandas

Сводка данных позволяет изменить их форму таким образом, чтобы их было намного легче понять или проанализировать. Часто сводные таблицы связаны с Microsoft Excel. Изменяющая сила сводки значительно упрощает понимание взаимосвязей в ваших наборах данных.

Синтаксис

Параметры

Столбец для агрегирования, необязательный параметр.

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

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

Читайте также:  Php http response body

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

Это скаляр, по умолчанию None. Значение для замены отсутствующих значений.

Это логическое значение, по умолчанию False. Он добавляет все строки/столбцы (например, для промежуточных/общих итогов).

Это логическое значение по умолчанию True. Не включайте столбцы, все записи которых являются NaN.

Это строка, по умолчанию « All «. Это имя строки/столбца, которые будут содержать итоги, когда поле равно True.

Это логическое значение, по умолчанию False. Этот аргумент применяется только в том случае, если какой-либо из группировщиков является категориальным.

Если True, то отображать наблюдаемые значения только для категориальных группировщиков. Если False, то отображаются все значения для категориальных группировщиков. Это изменилось в версии 0.25.0.

Пример сводной таблицы Pandas

Давайте создадим DataFrame.

Источник

pandas.DataFrame.pivot_table#

DataFrame. pivot_table ( values = None , index = None , columns = None , aggfunc = ‘mean’ , fill_value = None , margins = False , dropna = True , margins_name = ‘All’ , observed = False , sort = True ) [source] #

Create a spreadsheet-style pivot table as a DataFrame.

The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.

Parameters values list-like or scalar, optional

Column or columns to aggregate.

index column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values.

columns column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values.

aggfunc function, list of functions, dict, default numpy.mean

If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions. If margin=True , aggfunc will be used to calculate the partial aggregates.

fill_value scalar, default None

Value to replace missing values with (in the resulting pivot table, after aggregation).

margins bool, default False

If margins=True , special All columns and rows will be added with partial group aggregates across the categories on the rows and columns.

dropna bool, default True

Do not include columns whose entries are all NaN. If True, rows with a NaN value in any column will be omitted before computing margins.

margins_name str, default ‘All’

Name of the row / column that will contain the totals when margins is True.

observed bool, default False

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.

sort bool, default True

Specifies if the result should be sorted.

An Excel style pivot table.

Pivot without aggregation that can handle non-numeric data.

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.

Wide panel to long format. Less flexible but more user-friendly than melt.

Reference the user guide for more examples.

>>> df = pd.DataFrame("A": ["foo", "foo", "foo", "foo", "foo", . "bar", "bar", "bar", "bar"], . "B": ["one", "one", "one", "two", "two", . "one", "one", "two", "two"], . "C": ["small", "large", "large", "small", . "small", "large", "small", "small", . "large"], . "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], . "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]>) >>> df A B C D E 0 foo one small 1 2 1 foo one large 2 4 2 foo one large 2 5 3 foo two small 3 5 4 foo two small 3 6 5 bar one large 4 6 6 bar one small 5 8 7 bar two small 6 9 8 bar two large 7 9 

This first example aggregates values by taking the sum.

>>> table = pd.pivot_table(df, values='D', index=['A', 'B'], . columns=['C'], aggfunc=np.sum) >>> table C large small A B bar one 4.0 5.0 two 7.0 6.0 foo one 4.0 1.0 two NaN 6.0 

We can also fill missing values using the fill_value parameter.

>>> table = pd.pivot_table(df, values='D', index=['A', 'B'], . columns=['C'], aggfunc=np.sum, fill_value=0) >>> table C large small A B bar one 4 5 two 7 6 foo one 4 1 two 0 6 

The next example aggregates by taking the mean across multiple columns.

>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], . aggfunc='D': np.mean, 'E': np.mean>) >>> table D E A C bar large 5.500000 7.500000 small 5.500000 8.500000 foo large 2.000000 4.500000 small 2.333333 4.333333 

We can also calculate multiple types of aggregations for any given value column.

>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], . aggfunc='D': np.mean, . 'E': [min, max, np.mean]>) >>> table D E mean max mean min A C bar large 5.500000 9 7.500000 6 small 5.500000 9 8.500000 8 foo large 2.000000 5 4.500000 4 small 2.333333 6 4.333333 2 

Источник

pandas.pivot_table#

pandas. pivot_table ( data , values = None , index = None , columns = None , aggfunc = ‘mean’ , fill_value = None , margins = False , dropna = True , margins_name = ‘All’ , observed = False , sort = True ) [source] #

Create a spreadsheet-style pivot table as a DataFrame.

The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) on the index and columns of the result DataFrame.

Parameters data DataFrame values list-like or scalar, optional

Column or columns to aggregate.

index column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table index. If an array is passed, it is being used as the same manner as column values.

columns column, Grouper, array, or list of the previous

If an array is passed, it must be the same length as the data. The list can contain any of the other types (except list). Keys to group by on the pivot table column. If an array is passed, it is being used as the same manner as column values.

aggfunc function, list of functions, dict, default numpy.mean

If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names (inferred from the function objects themselves) If dict is passed, the key is column to aggregate and value is function or list of functions. If margin=True , aggfunc will be used to calculate the partial aggregates.

fill_value scalar, default None

Value to replace missing values with (in the resulting pivot table, after aggregation).

margins bool, default False

If margins=True , special All columns and rows will be added with partial group aggregates across the categories on the rows and columns.

dropna bool, default True

Do not include columns whose entries are all NaN. If True, rows with a NaN value in any column will be omitted before computing margins.

margins_name str, default ‘All’

Name of the row / column that will contain the totals when margins is True.

observed bool, default False

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.

sort bool, default True

Specifies if the result should be sorted.

An Excel style pivot table.

Pivot without aggregation that can handle non-numeric data.

Unpivot a DataFrame from wide to long format, optionally leaving identifiers set.

Wide panel to long format. Less flexible but more user-friendly than melt.

Reference the user guide for more examples.

>>> df = pd.DataFrame("A": ["foo", "foo", "foo", "foo", "foo", . "bar", "bar", "bar", "bar"], . "B": ["one", "one", "one", "two", "two", . "one", "one", "two", "two"], . "C": ["small", "large", "large", "small", . "small", "large", "small", "small", . "large"], . "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], . "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]>) >>> df A B C D E 0 foo one small 1 2 1 foo one large 2 4 2 foo one large 2 5 3 foo two small 3 5 4 foo two small 3 6 5 bar one large 4 6 6 bar one small 5 8 7 bar two small 6 9 8 bar two large 7 9 

This first example aggregates values by taking the sum.

>>> table = pd.pivot_table(df, values='D', index=['A', 'B'], . columns=['C'], aggfunc=np.sum) >>> table C large small A B bar one 4.0 5.0 two 7.0 6.0 foo one 4.0 1.0 two NaN 6.0 

We can also fill missing values using the fill_value parameter.

>>> table = pd.pivot_table(df, values='D', index=['A', 'B'], . columns=['C'], aggfunc=np.sum, fill_value=0) >>> table C large small A B bar one 4 5 two 7 6 foo one 4 1 two 0 6 

The next example aggregates by taking the mean across multiple columns.

>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], . aggfunc='D': np.mean, 'E': np.mean>) >>> table D E A C bar large 5.500000 7.500000 small 5.500000 8.500000 foo large 2.000000 4.500000 small 2.333333 4.333333 

We can also calculate multiple types of aggregations for any given value column.

>>> table = pd.pivot_table(df, values=['D', 'E'], index=['A', 'C'], . aggfunc='D': np.mean, . 'E': [min, max, np.mean]>) >>> table D E mean max mean min A C bar large 5.500000 9 7.500000 6 small 5.500000 9 8.500000 8 foo large 2.000000 5 4.500000 4 small 2.333333 6 4.333333 2 

Источник

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