- Как удалить многоиндексные столбцы или строки в dataframe Pandas?
- Создание набора данных
- Удаление строк или столбцов верхнего уровня
- Удаление столбцов или строк мультииндекса
- Сглаживание индексов
- Заключение
- MultiIndex / advanced indexing¶
- Hierarchical indexing (MultiIndex)В¶
- Creating a MultiIndex (hierarchical index) object¶
- Reconstructing the level labels¶
- Basic indexing on axis with MultiIndex¶
- Defined levels¶
- Data alignment and using reindex В¶
- Advanced indexing with hierarchical index¶
- Using slicers¶
- Иерархическое индексирование и уровни признаков / pd 6
- Изменение порядка и сортировка уровней
- Общая статистика по уровню
Как удалить многоиндексные столбцы или строки в dataframe Pandas?
Фреймы данных Pandas предоставляют возможность использования нескольких индексов для маркировки хранимых данных.
Это может использоваться как для столбцов, так и для строк, позволяя вам организовывать определенные типы данных гораздо более эффективным способом.
Можно выбрать различные значения на основе различных уровней индекса.
Чтобы отбросить столбцы или строки мультииндекса в датафрейме, можно использовать метод drop(), как и в случае со стандартными индексами.
Однако необходимо учитывать некоторые дополнительные моменты.
Создание набора данных
Как обычно, перед изучением работы метода drop() в многоиндексных датафреймах, необходимо создать такой, для чего можно использовать следующий код.
В этом примере данные были созданы с помощью функции np.arange() в сочетании с np.reshape() для получения матрицы 6 на 6.
После этого необходимо создать мультииндексы для столбцов и строк.
Существуют различные способы сделать это, но в примере он был создан из кортежей с помощью функции pd.MultiIndex.from_tuples().
После получения мультииндексных объектов dataframe создается обычным способом, используя эти элементы вместо векторов для индексов строк и столбцов.
Удаление строк или столбцов верхнего уровня
Исключение строк или столбцов первого уровня выполняется так же, как и в стандартном случае.
Просто используйте метод drop() объекта, указав в свойстве columns имя удаляемых столбцов или колонок и, аналогично, свойство index для строк.
Таким образом, для удаления столбца B и строки Y вы можете использовать следующую строку кода.
В качестве альтернативы, для удаления строк можно указать только имя строки в методе drop().
В случае со столбцами этого также можно добиться, указав имя и присвоив свойству axis значение 1.
Это требует одного шага для удаления столбцов и другого для строк.
С другой стороны, если вы хотите удалить более одного столбца или строки, вам просто нужно передать вектор с индексами, которые вы хотите удалить.
Поэтому для удаления столбцов A и B одновременно со строками X и Z вы можете ввести следующую команду.
Удаление столбцов или строк мультииндекса
Теперь, в случае, если мы хотим удалить столбцы C2 второго уровня, использование того, что было объяснено до сих пор, приведет к ошибке.
Чтобы избежать этого, необходимо указать через свойство level функции drop(), что вы хотите удалить столбец второго уровня.
То есть, присвоив свойству значение 1, как показано ниже.
На самом деле, в этом есть большой смысл, поскольку в случае, когда один и тот же тег используется в двух разных уровнях, Pandas не может знать, какой из них удалить. Поэтому необходимо указать уровень, на котором вы хотите его применить, если он не первый.
В случае с рядами процесс аналогичен предыдущему.
Как и для индексов первого уровня, также возможно удаление строк и столбцов с помощью одной инструкции. Однако они должны быть одного уровня.
Сглаживание индексов
В примере, после удаления строки и столбца второго уровня, наличие нескольких индексов является излишним.
Это можно решить, удалив лишние уровни с помощью метода droplevel() индексов.
Метод, единственным параметром которого является уровень, который вы хотите удалить из индексов, по умолчанию это первый уровень (0).
Использовать его просто, достаточно применить его к индексу и присвоить результат датафрейму, как показано в следующем примере.
Однако в данном случае может быть интереснее убрать индексы второго уровня.
В случае если вы хотите сохранить оба индекса, но удалить подуровни:
Заключение
В этой записи мы рассмотрели использование метода drop() для удаления столбцов или строк мультииндекса в фрейме данных Pandas.
Источник
MultiIndex / advanced indexing¶
See the Indexing and Selecting Data for general indexing documentation.
Whether a copy or a reference is returned for a setting operation may depend on the context. This is sometimes called chained assignment and should be avoided. See Returning a View versus Copy .
See the cookbook for some advanced strategies.
Hierarchical indexing (MultiIndex)В¶
Hierarchical / Multi-level indexing is very exciting as it opens the door to some quite sophisticated data analysis and manipulation, especially for working with higher dimensional data. In essence, it enables you to store and manipulate data with an arbitrary number of dimensions in lower dimensional data structures like Series (1d) and DataFrame (2d).
In this section, we will show what exactly we mean by “hierarchical” indexing and how it integrates with all of the pandas indexing functionality described above and in prior sections. Later, when discussing group by and pivoting and reshaping data , we’ll show non-trivial applications to illustrate how it aids in structuring data for analysis.
See the cookbook for some advanced strategies.
Creating a MultiIndex (hierarchical index) object¶
The MultiIndex object is the hierarchical analogue of the standard Index object which typically stores the axis labels in pandas objects. You can think of MultiIndex as an array of tuples where each tuple is unique. A MultiIndex can be created from a list of arrays (using MultiIndex.from_arrays() ), an array of tuples (using MultiIndex.from_tuples() ), a crossed set of iterables (using MultiIndex.from_product() ), or a DataFrame (using MultiIndex.from_frame() ). The Index constructor will attempt to return a MultiIndex when it is passed a list of tuples. The following examples demonstrate different ways to initialize MultiIndexes.
When you want every pairing of the elements in two iterables, it can be easier to use the MultiIndex.from_product() method:
You can also construct a MultiIndex from a DataFrame directly, using the method MultiIndex.from_frame() . This is a complementary method to MultiIndex.to_frame() .
As a convenience, you can pass a list of arrays directly into Series or DataFrame to construct a MultiIndex automatically:
All of the MultiIndex constructors accept a names argument which stores string names for the levels themselves. If no names are provided, None will be assigned:
This index can back any axis of a pandas object, and the number of levels of the index is up to you:
We’ve “sparsified” the higher levels of the indexes to make the console output a bit easier on the eyes. Note that how the index is displayed can be controlled using the multi_sparse option in pandas.set_options() :
It’s worth keeping in mind that there’s nothing preventing you from using tuples as atomic labels on an axis:
The reason that the MultiIndex matters is that it can allow you to do grouping, selection, and reshaping operations as we will describe below and in subsequent areas of the documentation. As you will see in later sections, you can find yourself working with hierarchically-indexed data without creating a MultiIndex explicitly yourself. However, when loading data from a file, you may wish to generate your own MultiIndex when preparing the data set.
Reconstructing the level labels¶
The method get_level_values() will return a vector of the labels for each location at a particular level:
Basic indexing on axis with MultiIndex¶
One of the important features of hierarchical indexing is that you can select data by a “partial” label identifying a subgroup in the data. Partial selection “drops” levels of the hierarchical index in the result in a completely analogous way to selecting a column in a regular DataFrame:
See Cross-section with hierarchical index for how to select on a deeper level.
Defined levels¶
The MultiIndex keeps all the defined levels of an index, even if they are not actually used. When slicing an index, you may notice this. For example:
This is done to avoid a recomputation of the levels in order to make slicing highly performant. If you want to see only the used levels, you can use the get_level_values() method.
To reconstruct the MultiIndex with only the used levels, the remove_unused_levels() method may be used.
Data alignment and using reindex В¶
Operations between differently-indexed objects having MultiIndex on the axes will work as you expect; data alignment will work the same as an Index of tuples:
The reindex() method of Series / DataFrames can be called with another MultiIndex , or even a list or array of tuples:
Advanced indexing with hierarchical index¶
Syntactically integrating MultiIndex in advanced indexing with .loc is a bit challenging, but we’ve made every effort to do so. In general, MultiIndex keys take the form of tuples. For example, the following works as you would expect:
Note that df.loc[‘bar’, ‘two’] would also work in this example, but this shorthand notation can lead to ambiguity in general.
If you also want to index a specific column with .loc , you must use a tuple like this:
You don’t have to specify all levels of the MultiIndex by passing only the first elements of the tuple. For example, you can use “partial” indexing to get all elements with bar in the first level as follows:
This is a shortcut for the slightly more verbose notation df.loc[(‘bar’,),] (equivalent to df.loc[‘bar’,] in this example).
“Partial” slicing also works quite nicely.
You can slice with a вЂrange’ of values, by providing a slice of tuples.
Passing a list of labels or tuples works similar to reindexing:
It is important to note that tuples and lists are not treated identically in pandas when it comes to indexing. Whereas a tuple is interpreted as one multi-level key, a list is used to specify several keys. Or in other words, tuples go horizontally (traversing levels), lists go vertically (scanning levels).
Importantly, a list of tuples indexes several complete MultiIndex keys, whereas a tuple of lists refer to several values within a level:
Using slicers¶
You can slice a MultiIndex by providing multiple indexers.
You can provide any of the selectors as if you are indexing by label, see Selection by Label , including slices, lists of labels, labels, and boolean indexers.
You can use slice(None) to select all the contents of that level. You do not need to specify all the deeper levels, they will be implied as slice(None) .
As usual, both sides of the slicers are included as this is label indexing.
You should specify all axes in the .loc specifier, meaning the indexer for the index and for the columns. There are some ambiguous cases where the passed indexer could be mis-interpreted as indexing both axes, rather than into say the MultiIndex for the rows.
Источник
Иерархическое индексирование и уровни признаков / pd 6
Иерархическое индексирование — это важная особенность pandas, поскольку она позволяет иметь несколько уровней индексов в одной оси. С ее помощью можно работать с данными в большом количестве измерений, по-прежнему используя для этого структуру данных из двух измерений.
Начнем с простого примера, создав Series с двумя массивами индексов — структуру с двумя уровнями.
За счет спецификации иерархического индексирования, выбор подмножеств значений в таком случае заметно упрощен. Можно выбрать значения для определенного значения первого индекса стандартным способом:
Или же значения для конкретного значения во втором индекса — таким:
Если необходимо конкретное значение, просто указываются оба индекса.
Иерархическое индексирование играет важную роль в изменении формы данных и групповых операциях, таких как сводные таблицы. Например, данные могут быть перестроены и использованы в объекте Dataframe с помощью функции unstack() . Она конвертирует Series с иерархическими индексами в простой Dataframe , где второй набор индексов превращается в новые колонки.
down | left | right | up | |
---|---|---|---|---|
blue | 0.408367 | NaN | NaN | 0.081480 |
red | 0.374153 | 0.325975 | NaN | 0.465264 |
white | 0.512268 | NaN | 0.639885 | 0.661039 |
Если необходимо выполнить обратную операцию — превратить Dataframe в Series , — используется функция stack() .
ball | pen | pencil | paper | |
---|---|---|---|---|
red | 0 | 1 | 2 | 3 |
blue | 4 | 5 | 6 | 7 |
yellow | 8 | 9 | 10 | 11 |
white | 12 | 13 | 14 | 15 |
В Dataframe можно определить иерархическое индексирование для строк и колонок. Для этого необходимо определить массив массивов для параметров index и columns .
pen | paper | ||||
---|---|---|---|---|---|
1 | 2 | 1 | 2 | ||
white | up | 1.562883 | 0.919727 | -0.397509 | -0.314159 |
down | 0.580848 | 1.124744 | 0.741454 | -0.035455 | |
red | up | -1.721348 | 0.989703 | -1.454304 | -0.249718 |
down | -0.113246 | -0.441528 | -0.105028 | 0.285786 |
Изменение порядка и сортировка уровней
Иногда потребуется поменять порядок уровней на оси или отсортировать значения на определенном уровне.
Функция swaplevel() принимает в качестве аргументов названия уровней, которые необходимо поменять относительно друг друга и возвращает новый объект с соответствующими изменениями, оставляя данные в том же состоянии.
objects | pen | paper | |||
---|---|---|---|---|---|
id | 1 | 2 | 1 | 2 | |
colors | status | ||||
white | up | 1.562883 | 0.919727 | -0.397509 | -0.314159 |
down | 0.580848 | 1.124744 | 0.741454 | -0.035455 | |
red | up | -1.721348 | 0.989703 | -1.454304 | -0.249718 |
down | -0.113246 | -0.441528 | -0.105028 | 0.285786 |
objects | pen | paper | |||
---|---|---|---|---|---|
id | 1 | 2 | 1 | 2 | |
status | colors | ||||
up | white | 1.562883 | 0.919727 | -0.397509 | -0.314159 |
down | white | 0.580848 | 1.124744 | 0.741454 | -0.035455 |
up | red | -1.721348 | 0.989703 | -1.454304 | -0.249718 |
down | red | -0.113246 | -0.441528 | -0.105028 | 0.285786 |
А функция sort_index() сортирует данные для конкретного уровня, указанного в параметрах.
objects | pen | paper | |||
---|---|---|---|---|---|
id | 1 | 2 | 1 | 2 | |
colors | status | ||||
red | down | -0.113246 | -0.441528 | -0.105028 | 0.285786 |
up | -1.721348 | 0.989703 | -1.454304 | -0.249718 | |
white | down | 0.580848 | 1.124744 | 0.741454 | -0.035455 |
up | 1.562883 | 0.919727 | -0.397509 | -0.314159 |
Общая статистика по уровню
У многих статистических методов для Dataframe есть параметр level , в котором нужно определить, для какого уровня нужно определить статистику.
Например, если нужна статистика для первого уровня, его нужно указать в параметрах.
objects | pen | paper | ||
---|---|---|---|---|
id | 1 | 2 | 1 | 2 |
colors | ||||
white | 2.143731 | 2.044471 | 0.343945 | -0.349614 |
red | -1.834594 | 0.548174 | -1.559332 | 0.036068 |
Если же она необходима для конкретного уровня колонки, например, id , тогда требуется задать параметр axis и указать значение 1.
Источник