unstack pandas что делает
Изменение формы DataFrame для панд с использованием стека, разборки и расплавления
Панды используют различные методы для изменения формы и ряда данных. Давайте посмотрим на некоторые из этого метода изменения формы.
Давайте сначала импортируем фрейм данных.
# модуль импорта панд
import pandas as pd
# создание кадра данных
# было напечатано первые 5 строк
Выход:
Используя метод stack ():
Метод стека работает с объектами MultiIndex в DataFrame, он возвращает DataFrame с индексом с новым внутренним уровнем меток строк. Это меняет широкий стол на длинный стол.
# модуль импорта панд
import pandas as pd
# создание кадра данных
df = pd.read_csv( «nba.csv» )
# изменить форму данных с помощью метода stack ()
print (df_stacked.head( 26 ))
Выход:
Использование метода unstack ():
unstack аналогичен методу стека. Он также работает с многоиндексными объектами в фрейме данных, создавая измененный DataFrame с новым внутренним уровнем меток столбцов.
# модуль импорта панд
import pandas as pd
# создание кадра данных
df = pd.read_csv( «nba.csv» )
print (df_unstacked.head( 10 ))
Используя метод melt() :
Растопить в пандах изменить форму данных из широкого формата в длинный формат. Он использует «id_vars [‘col_names’]» для объединения данных с именами столбцов.
# модуль импорта панд
import pandas as pd
# создание кадра данных
df = pd.read_csv( «nba.csv» )
# занимает две колонки «Имя» и «Команда»
print (df_melt.head( 10 ))
Выход:
Русские Блоги
stack、unstack
Давайте посмотрим, как эти два метода переставляют таблицу данных.
Экспериментальные данные:
Как видите, после использования метода стека исходный индекс таблицы данных становится новым внешним индексом ряда, а исходное имя столбца становится вторичным индексом.
Его метод перестановки основан на:
Индекс старой таблицы 1 + имя столбца + значение
…
имя столбца + значение
…
Индекс n + имя столбца + значение старой таблицы
…
имя столбца + значение
…
Метод unstack может полностью изменить работу стека, а также имеет собственный метод перестановки
pivot、melt
Основные параметры пивота
index: Метка для индексации новых кадров
columns: Метка для создания новых рамных столбцов
values: Значение, используемое для заполнения нового значения кадра
Сводная таблица преобразует длинную таблицу в широкую таблицу, а значения без значения заполняются пропущенными значениями.
Тем не менее, индекс и столбцы pivot могут принимать только один столбец в качестве параметра, поэтому вы можете использовать pivot_table вместо этого при необходимости.
Основные параметры расплава
id_vars: Идентификационный столбец
value_vars: Столбцы для интеграции
var_name: Имя столбца столбца value_vars
value_name: Имя столбца значения
col_level: Уровень индекса столбца (требуется, если столбец является многократным индексом)
Значение, изначально находящееся в той же строке, что и A (столбец идентификации), отображается в столбце значений и соответствующем значении столбца переменнойB«Является ли имя столбца исходного значения
Здесь мы используем melt для преобразования вышеуказанной таблицы данных в длинную таблицу
Интеллектуальная рекомендация
AlamoFire Source Severtation Series (12) ось времени (временная шкала)
Эта статья приносит некоторые идеи о временной шкале в AlamoFire Преступность Перевод Timeline означает, что временная шкала может представлять событие с начала до конца узла времени. Концепция времен.
Анализ разницы между iOS initWithFrame, initWithCoder, awakeFromNib
Исследование соответствия типовых версий рамы
Categories
Introduction
Pandas is a popular python library for data analysis. It provides a façade on top of libraries like numpy and matplotlib, which makes it easier to read and transform data. It provides the abstractions of DataFrames and Series, similar to those in R.
In Pandas data reshaping means the transformation of the structure of a table or vector (i.e. DataFrame or Series) to make it suitable for further analysis. Some of Pandas reshaping capabilities do not readily exist in other environments (e.g. SQL or bare bone R) and can be tricky for a beginner.
In this post, I’ll exemplify some of the most common Pandas reshaping functions and will depict their work with diagrams.
Pivot
The pivot function is used to create a new derived table out of a given one. Pivot takes 3 arguements with the following names: index, columns, and values. As a value for each of these parameters you need to specify a column name in the original table. Then the pivot function will create a new table, whose row and column indices are the unique values of the respective parameters. The cell values of the new table are taken from column given as the values parameter.
A bit foggy? Let’s give an example. Assume that we are given the following small table:
Although the semantics doesn’t matter in this example, you can think of it as a table of items we want to sell. The Item column contains the item names, USD is the price in US dollars and EU is the price in euros. Each client can be classified as Gold, Silver or Bronze customer and this is specified in the CType column.
The following code snippet creates the depicted DataFrame. Note that we will assume these imports are present in all code snippets throughout this article.
In such a table, it is not easy to see how the USD price varies over different customer types. We may like to reshape/pivot the table so that all USD prices for an item are on the row to compare more easily. With Pandas, we can do so with a single line:
Pivoting in action.
In other words, the value of USD for every row in the original table has been transferred to the new table, where its row and column match the Item and CType of its original row. Cells in the new table which do not have a matching entry in the original one are set with NaN.
As an example the following lines perform equivalent queries on the original and pivoted tables:
Note that in this example the pivoted table does not contain any information about the EU column! Indeed, we can’t see those euro symbols anywhere! Thus, the pivoted table is a simplified version of the original data and only contains information about the columns we specified as parameters to the pivot method.
Pivoting By Multiple Columns
We can use this hierarchical column index to filter the values of a single column from the original table. For example p.USD returns a pivoted DataFrame with the USD values only and it is equivalent to the pivoted DataFrame from the previous section.
To exemplify hierarchical indices, the expression p.USD.Bronze selects the first column in the pivoted table.
As a further example the following queries on the original and pivoted tables are equivalent:
Common Mistake in Pivoting
Common error in pivoting
In this example we have two rows with the same values (“Item0” and “Gold”) for the Item and CType columns. The pivot method can not know what should be the value of the corresponding value in the pivoted table. Thus, it throws an exception with the following message:
The following code reproduces the issue:
Hence, before calling pivot we need to ensure that our data does not have rows with duplicate values for the specified columns. If we can’t ensure this we may have to use the pivot_table method instead.
Pivot Table
The pivot_table method comes to solve this problem. It works like pivot, but it aggregates the values from rows with duplicate entries for the specified columns. In other words, in the previous example we could have used the mean, the median or another aggregation function to compute a single value from the conflicting entries. This is depicted in the example below.
Pivoting by a single column
In essence pivot_table is a generalisation of pivot, which allows you to aggregate multiple values with the same destination in the pivoted table.
Stack/Unstack
In fact pivoting a table is a special case of stacking a DataFrame. Let us assume we have a DataFrame with MultiIndices on the rows and columns. Stacking a DataFrame means moving (also rotating or pivoting) the innermost column index to become the innermost row index. The inverse operation is called unstacking. It means moving the innermost row index to become the innermost column index. The following diagram depicts the operations:
In this example, we look at a DataFrame with 2-level hierarchical indices on both axes. Stacking takes the most-inner column index (i.e. c00, c01, c10), makes it the most inner row index and reshuffles the cell values accordingly. Inversely, unstacking moves the inner row indices (i.e. r00, r01) to the columns.
Typically, stacking makes the DataFrame taller, as it is “stacking” data in fewer columns and more rows. Similarly, unstacking usually makes it shorter and wider or broader. The following reproduces the example:
In fact Pandas allows us to stack/unstack on any level of the index so our previous explanation was a bit simplified :). Thus, in the previous example we could have stacked on the outermost index level as well! However, the default (and most typical case) is to stack/unstack on the innermost index level.
Stacking and unstacking can also be applied to data with flat (i.e. non-hierchical) indices. In this case, one of the indices is de facto removed (the columns index if stacking, and the rows if unstacking) and its values are nested in the other index, which is now a MultiIndex. Therefore, the result is always a Series with a hierarchical index. The following example demonstrates this:
In this example we take a DataFrame similar to the one from the beginning. Instead of pivoting, this time we stack it, and we get a Series with a MultiIndex composed of the initial index as first level, and the table columns as a second. Unstacking can help us get back to our original data structure.
Pandas Tutorial – Stack(), Unstack() and Melt()
Importing Pandas Library
Initially, we will load the Pandas library.
Pandas Stack : stack()
The stack function of pandas is used for stacking the levels from columns to index.
Syntax
pandas.DataFrame.stack(level,dropna)
level : int, str, list, default – Here the levels from where columns are stacked are provided.
dropna : bool, default True – This parameter is used to decide whether null values should be dropped or not.
Example 1: Using Pandas Stack on single level column
In this example, we will be applying stack() function on single level column. We have created a dataframe and then the pandas stack() function is applied over the column.
Example 2: Using multi-level columns with pandas stack()
Here multindex dataframe is created and then the stack function is applied.
Pandas Unstack : unstack()
The pandas unstack() function pivots a level of hierarchical index labels.
Syntax
pandas.DataFrame.unstack(level,fill_value)
fill_value : int, str or dict : Using this parameter, we can fill the null values usin this parameter.
Example 1: Using series data with pandas unstack function
In this example, series data is used for applying the unstacking operation.
The unstack function has a parameter known as level. We have used this parameter for performing the unstack operation.
Example 2: Applying unstack() function on dataframe
In this example, pandas unstack() function is applied to dataframe data by using level parameter.
Pandas Melt : melt()
Pandas melt() function is used for unpivoting a DataFrame from wide to long format.
Syntax
pandas.DataFrame.melt(id_vars=None, value_vars=None, var_name=None, value_name=’value’, col_level=None)
id_vars : tuple, list, or ndarray, optional – Here the columns are passed that will be used as identifier values.
value_vars : tuple, list, or ndarray, optional – In this parameter, columns that we want to melt are selected.
var_name : scalar – This is the name used for the variable column.
value_name : scalar,default value – This is the name used for value column
col_level : int or str, optional – If columns are a MultiIndex then use this level to melt.
Example 1: Using single level dataframes for pandas melt() function
In this example, the melt function of pandas is applied on single level dataframes.
Unstack pandas что делает
При работе с таблицами Pandas порой приходится их видоизменять, в частности, когда таблица многоуровневая. В этой статье мы расскажем вам об основных функциях Pandas для изменения формы таблицы. К этим функциям относятся: pivot для создания сводной таблицы, stack/unstack для добавления/удаления уровня и melt для преобразования столбцов в строки.
Сводные таблицы с Pivot
Результат pivot на таблицах Pandas
Пример с кодом на Python для создания сводной таблицы:
Добавляем и удаляем уровни
С pivot тесно связаны связанные методы stack и unstack как для объектов Series, так и DataFrame. Эти методы предназначены для совместной работы с многоуровневыми таблицами. Под уровнем подразумевается столбец в индексе. Вот что в сущности делают эти методы:
Результат удаления уровня
Код на Python для добавления уровня в таблице Pandas:
Из столбцов в переменные
Результат преобразования melt
Следующий пример на Python демонстрирует результат Pandas-функции melt:
Еще больше подробностей о преобразовании таблиц Pandas в рамках анализа данных и задач Data Science на реальных примерах вы узнаете на нашем специализированном курсе «DPREP: Подготовка данных для Data Mining на Python» в лицензированном учебном центре обучения и повышения квалификации IT-специалистов в Москве.