pandas.DataFrame.loc#
Access a group of rows and columns by label(s) or a boolean array.
.loc[] is primarily label based, but may also be used with a boolean array.
Allowed inputs are:
A single label, e.g. 5 or ‘a’ , (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
A list or array of labels, e.g. [‘a’, ‘b’, ‘c’] .
A slice object with labels, e.g. ‘a’:’f’ .
Note that contrary to usual python slices, both the start and the stop are included
A boolean array of the same length as the axis being sliced, e.g. [True, False, True] .
An alignable boolean Series. The index of the key will be aligned before masking.
An alignable Index. The Index of the returned selection will be the input.
A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above)
If any items are not found.
If an indexed key is passed and its index is unalignable to the frame index.
Access a single value for a row/column label pair.
Access group of rows and columns by integer position(s).
Returns a cross-section (row(s) or column(s)) from the Series/DataFrame.
Access group of values using labels.
Getting values
Single label. Note this returns the row as a Series.
List of labels. Note using [[]] returns a DataFrame.
Single label for row and column
Slice with labels for row and single label for column. As mentioned above, note that both the start and stop of the slice are included.
Boolean list with the same length as the row axis
Alignable boolean Series:
Index (same behavior as df.reindex )
Conditional that returns a boolean Series
Conditional that returns a boolean Series with column labels specified
Callable that returns a boolean Series
Setting values
Set value for all items matching the list of labels
Set value for an entire row
Set value for an entire column
Set value for rows matching callable condition
Getting values on a DataFrame with an index that has integer labels
Another example using integers for the index
Slice with integer labels for rows. As mentioned above, note that both the start and stop of the slice are included.
Getting values with a MultiIndex
A number of examples using a DataFrame with a MultiIndex
Single label. Note this returns a DataFrame with a single index.
Single index tuple. Note this returns a Series.
Single label for row and column. Similar to passing in a tuple, this returns a Series.
Single tuple. Note using [[]] returns a DataFrame.
Single tuple for the index with a single label for the column
Slice from index tuple to single label
Slice from index tuple to index tuple
Please see the user guide for more details and explanations of advanced indexing.
Работа с индексами — Python: Pandas
Фильтрация значений и оперирование с их подмножествами используются в задачах обработки, подготовки и анализа данных. В этом уроке мы познакомимся c правилами индексирования основных объектов Series и DataFrame , а также узнаем, как с их помощью осуществлять подвыборки нужных строк и столбцов в табличных данных.
Структура объекта DataFrame
Рассмотрим объект DataFrame . Он состоит из набора столбцов, каждый из которых является объектом Series :
Применим функцию type() к столбцу df_orders :
Объект Series спроектирован, чтобы хранить одномерные структуры данных. Он состоит из двух связанных между собой массивов: меток и значений:
Выбрать несколько столбцов можно следующим образом:
При выборе нескольких столбцов мы будем снова получать тип данных DataFrame.
Иногда легче выбросить несколько столбцов, чем перечислять необходимые. В этом случае нужно использовать метод drop() :
В методе drop() нужно задавать значение параметра axis . Значение 0 будет указывать, что нужно исключить некоторые строки. Значение 1 указывает на исключение столбцов.
Метод drop() возвращает новый объект DataFrame и оставляет без изменений исходный.
Индексы объектов DataFrame и Series
У каждой строки объекта DataFrame или значения у Series есть индекс. Индекс может быть как числом, так и строкой. Список индексов объектов DataFrame и Series можно получить с помощью атрибута index :
Если нужно, можно изменить значение индексов и имя столбца с индексами:
Строковые индексы обычно называют метки или ключи:
Методы получения значений по индексу
Разберем следующие методы:
- loc() — метод выбора данных на основе меток строк
- iloc() — метод выбора строк согласно их числовой позиции
Выберем одну строку из объекта DataFrame по ее метке:
Выберем несколько строк:
Выберем одну строку:
Выберем несколько строк:
Фильтрация строк и столбцов одновременно
Методы loc() и iloc() позволяют выполнять фильтрацию по строкам и столбцам одновременно. Пример для loc() :
Пример для iloc() :
Как и при использовании методов отдельно для строк и столбцов, метод loc() ожидает на вход метки, а iloc() — номера позиций строк и столбцов.
Срезы
Срезы позволяют получать совокупности строк в определенном диапазоне. Пример:
В срез данных попали все строки между позициями 1 и 3 включительно. Позиции 1 и 3 соответствуют меткам 'b' и 'd'. Можно строить более интересные срезы:
В данный срез попала каждая вторая строка между строками с метками 'b' и 'f'.
Можно получать срезы со строками и столбцами одновременно:
В срез попала каждая вторая строка между строками с метками 'b' и 'f' и столбцы с метками от 'shop_1' до 'shop_3' включительно.
Аналогично получаются срезы с помощью метода iloc() . Приведем пример, который совпадает по результату с примером выше:
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
Df loc python что это
Мы начинаем знакомиться с Pandas — главной библиотекой Python для анализа данных.
Это очень удобный и не самый сложный в освоении инструмент дата-журналиста. Он позволяет работать с данными в привычном для нас табличном виде. В Pandas можно изучить набор данных, почистить его, внести изменения, проанализировать и сделать выводы, построить графики и многое другое.
В отличие от Excel, где тоже широкие возможности для работы с данными, Pandas справится даже с очень большими файлами, в которых сотни тысяч и миллионы строк. Стандартному Excel такое не под силу, как и работа с файлами в формате json — именно в таком формате часто хранятся открытые данные. Например, на сайте ГосРасходы данные о государственных контрактах и субсидиях можно выгрузить только в json.
Мы посвятим библиотеке Pandas несколько уроков. Сегодня будет первое знакомство: мы научимся делать самые базовые вещи в Pandas, с которыми уже можно анализировать реальные данные.
1. Создаём датафреймы с нуля
Для начала загрузим библиотеку pandas, сокращенно будем обращаться к ней pd.
Если вы работаете не через Анаконду, загружайте Pandas командой pip3 install pandas.
В Pandas данные представлены в виде датафрейма, или таблицы с данными. Её можно создать с нуля, например, из словарей, списков или кортежей.
Создадим свой первый датафрейм для трех крупнейших городов России. Перед нами словарь, в котором ключами являются city и population, а значениями — списки с названиями этих городов и численностью населения, которая им соответствует.
В первом столбце указан индекс (порядковый номер), а остальное выглядит, как привычная таблица.
Также можно создать датафрейм из списка списков.
На этот раз значения записались построчно, и удобнее будет поменять местами строки и столбцы, то есть транспонировать.
Теперь мы знаем, как создать датафрейм с нуля. Но на практике его обычно приходится загружать из файла в форматах excel, csv или json.
2. Создаем датафрейм из файла
Сегодня мы будем работать с данными по смертности людей от разных причин. Перейдем на сайт Института оценки показателей здоровья США и выберем нужные показатели смертности по странам.
Выберем такие показатели:
- Location: Countries and territories (Страны и территории)
- Year: 2000-2019
- Content: Cause (причина смерти)
- Age: All ages
- Metric: Rate (число смертей от определенной причины на 100 тысяч жителей)
- Measure: Deaths (смерти)
- Sex: Male, Female, Both
- Cause: level 2 causes (2 уровень детализации причин смерти)
Дальше кликнем Download csv (скачать в формате csv).
Нужно поставить галочки, соглашаясь не использовать данные в коммерческих целях, выбрать Names и ввести почту.
Данные могут прийти не сразу, поэтому тот же самый датасет можно скачать по ссылке. Это большой датасет на 260 тысяч строк, с которым было бы непросто работать в Excel.
Скопируем путь к файлу на компьютере и загрузим его сразу в датафрейм с помощью метода pd.read_csv().
Выведем первые 5 строк датафрейма методом .head().
Чтобы вывести произвольное число строк, укажем нужное число в скобках.
Последние строки выводятся методом .tail().
Метод df.info() дает описание датафрейма: сколько в нем строк и столбцов, какие типы данных содержатся, сколько не пустых значений (non-null), сколько памяти занимает.
Если мы хотим только узнать, сколько в нем строк и столбцов, используем атрибут shape.
Метод describe дает статистику по числовым столбцам: среднее, максимум и минимум, квартили, стандартное отклонение.
Если нам для статистики нужны не только числовые столбцы, но и все остальные, добавим аргумент all.
Тогда к таблице добавятся поля unique (сколько в столбце уникальных значений), top (какое значение встречается чаще всего) и freq (сколько раз встречается самое частое значение).
У нас в датафрейме нет пустых значений (missing values, NA), но часто они бывают в реальных данных, «загрязняют» их и мешают с ними работать. От пустых значений можно избавиться методом dropna.
3. Фильтруем датафрейм по названию столбца и индексам
Выбрать определенный столбец можно двумя способами:
Также можно вывести на экран сразу несколько столбцов, обернув их в двойные квадратные скобки.
Ещё для выбора столбцов и строк существует методы loc и iloc. Loc — для выбора по названию, iloc — по индексу (порядковому номеру).
Если нам нужны только строки с 100 по 110, пропишем это условие слева.
Если мы хотим выбрать столбцы и строки не по названию, а по номеру, задействуем метод iloc. Это бывает полезно, например, когда названия столбцов слишком длинные.
Важно: в методе loc включаются все указанные в условии числа, поэтому мы видим строку 110, а в iloc правый конец исключается (как в стандартных срезах в Python), поэтому последняя строка, которую мы видим — 109. Чтобы вывести на экран строки 100:110, нужно было бы указать df.iloc[100:111, 0:3].
4. Фильтруем датафрейм по условиям
В Pandas очень удобно выбирать данные по условию. Например, нам нужны показатели смертности только для Both sexes, обоих полов.
Или по трем условиям: оба пола, только 2019 год, только сердечно-сосудистые заболевания.
Или по четырем: оба пола, только 2019 год, только сердечно-сосудистые заболевания, только больше 600 смертей на 100 тысяч жителей.
Мы видим страны с самой высокой смертностью от сердечно-сосудистых болезней. Cохраним результат в отдельный датафрейм и назовем его cardio.
И отсортируем его по показателю смертности от сердечно-сосудистых болезней. Оказывается, чаще всего от проблем с сердцем умирают в Болгарии.
Можно задать и так, чтобы соблюдалось или одно условие, или другое с помощью оператора «или»:
Если мы не знаем точно, как называется причина смерти, либо название слишком длинное, удобно использовать метод contains (содержит). Метод str.contains(«HIV») выдаст нам строки, в которых упоминается HIV (ВИЧ).
Если нам, наоборот, нужны строки, в которых НЕ упоминается ВИЧ, то можно добавить либо условие False в конце, либо знак
5. Удаляем, добавляем столбцы, меняем названия
Видно, что значения в столбцах measure, metric, age одинаковые. Также мы не будем работать с столбцами lower и upper (нижняя оценка показателя смертности и высокая), поэтому их можно удалить. Для этого используем метод drop.
Чтобы удалить несколько столбцов, обернем их в квадратные скобки.
Аргумент axis =1 показывает, что удалить нужно именно столбец (1 — столбцы, 0 — строки).
Теперь научимся добавлять столбцы. Например, добавим столбец, в котором будут храниться значения val, но только округленные до одной десятой.
Переименовать столбцы тоже несложно. Переименуем, например, val в value.
6. Сохраняем датафрейм
Датафрейм можно сохранить в csv или xlsx и работать с ним дальше в любой программе. Название файла должно быть уникальным, иначе если у вас на компьютере уже есть файл с таким названием, то он перезапишется.
Вот мы и освоили необходимым минимум для работы в Pandas. Тетрадь с этого урока можно скачать здесь, а задать вопросы и пообщаться — в чате «Мастерской» в Telegram.
Name already in use
pandas / doc / source / user_guide / indexing.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Indexing and selecting data
The axis labeling information in pandas objects serves many purposes:
- Identifies data (i.e. provides metadata) using known indicators, important for analysis, visualization, and interactive console display.
- Enables automatic and explicit data alignment.
- Allows intuitive getting and setting of subsets of the data set.
In this section, we will focus on the final point: namely, how to slice, dice, and generally get and set subsets of pandas objects. The primary focus will be on Series and DataFrame as they have received more development attention in this area.
The Python and NumPy indexing operators [] and attribute operator . provide quick and easy access to pandas data structures across a wide range of use cases. This makes interactive work intuitive, as there’s little new to learn if you already know how to deal with Python dictionaries and NumPy arrays. However, since the type of the data to be accessed isn’t known in advance, directly using standard operators has some optimization limits. For production code, we recommended that you take advantage of the optimized pandas data access methods exposed in this chapter.
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 :ref:`Returning a View versus Copy <indexing.view_versus_copy>` .
See the :ref:`MultiIndex / Advanced Indexing <advanced>` for MultiIndex and more advanced indexing documentation.
Different choices for indexing
Object selection has had a number of user-requested additions in order to support more explicit location based indexing. pandas now supports three types of multi-axis indexing.
.loc is primarily label based, but may also be used with a boolean array. .loc will raise KeyError when the items are not found. Allowed inputs are:
- A single label, e.g. 5 or ‘a’ (Note that 5 is interpreted as a label of the index. This use is not an integer position along the index.).
- A list or array of labels [‘a’, ‘b’, ‘c’] .
- A slice object with labels ‘a’:’f’ (Note that contrary to usual Python slices, both the start and the stop are included, when present in the index! See :ref:`Slicing with labels <indexing.slicing_with_labels>` and :ref:`Endpoints are inclusive <advanced.endpoints_are_inclusive>` .)
- A boolean array (any NA values will be treated as False ).
- A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above).
.iloc is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. .iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing. (this conforms with Python/NumPy slice semantics). Allowed inputs are:
- An integer e.g. 5 .
- A list or array of integers [4, 3, 0] .
- A slice object with ints 1:7 .
- A boolean array (any NA values will be treated as False ).
- A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above).
.loc , .iloc , and also [] indexing can accept a callable as indexer. See more at :ref:`Selection By Callable <indexing.callable>` .
Getting values from an object with multi-axes selection uses the following notation (using .loc as an example, but the following applies to .iloc as well). Any of the axes accessors may be the null slice : . Axes left out of the specification are assumed to be : , e.g. p.loc[‘a’] is equivalent to p.loc[‘a’, :] .
Object Type | Indexers |
---|---|
Series | s.loc[indexer] |
DataFrame | df.loc[row_indexer,column_indexer] |
As mentioned when introducing the data structures in the :ref:`last section <basics>` , the primary function of indexing with [] (a.k.a. __getitem__ for those familiar with implementing class behavior in Python) is selecting out lower-dimensional slices. The following table shows return type values when indexing pandas objects with [] :
Object Type | Selection | Return Value Type |
---|---|---|
Series | series[label] | scalar value |
DataFrame | frame[colname] | Series corresponding to colname |
Here we construct a simple time series data set to use for illustrating the indexing functionality:
None of the indexing functionality is time series specific unless specifically stated.
Thus, as per above, we have the most basic indexing using [] :
You can pass a list of columns to [] to select columns in that order. If a column is not contained in the DataFrame, an exception will be raised. Multiple columns can also be set in this manner:
You may find this useful for applying a transform (in-place) to a subset of the columns.
pandas aligns all AXES when setting Series and DataFrame from .loc , and .iloc .
This will not modify df because the column alignment is before value assignment.
The correct way to swap column values is by using raw values:
You may access an index on a Series or column on a DataFrame directly as an attribute:
- You can use this access only if the index element is a valid Python identifier, e.g. s.1 is not allowed. See here for an explanation of valid identifiers.
- The attribute will not be available if it conflicts with an existing method name, e.g. s.min is not allowed, but s[‘min’] is possible.
- Similarly, the attribute will not be available if it conflicts with any of the following list: index , major_axis , minor_axis , items .
- In any of these cases, standard indexing will still work, e.g. s[‘1’] , s[‘min’] , and s[‘index’] will access the corresponding element or column.
If you are using the IPython environment, you may also use tab-completion to see these accessible attributes.
You can also assign a dict to a row of a DataFrame :
You can use attribute access to modify an existing element of a Series or column of a DataFrame, but be careful; if you try to use attribute access to create a new column, it creates a new attribute rather than a new column and will this raise a UserWarning :
The most robust and consistent way of slicing ranges along arbitrary axes is described in the :ref:`Selection by Position <indexing.integer>` section detailing the .iloc method. For now, we explain the semantics of slicing using the [] operator.
With Series, the syntax works exactly as with an ndarray, returning a slice of the values and the corresponding labels:
Note that setting works as well:
With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.
Selection by label
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 :ref:`Returning a View versus Copy <indexing.view_versus_copy>` .
String likes in slicing can be convertible to the type of the index and lead to natural slicing.
pandas provides a suite of methods in order to have purely label based indexing. This is a strict inclusion based protocol. Every label asked for must be in the index, or a KeyError will be raised. When slicing, both the start bound AND the stop bound are included, if present in the index. Integers are valid labels, but they refer to the label and not the position.
The .loc attribute is the primary access method. The following are valid inputs:
- A single label, e.g. 5 or ‘a’ (Note that 5 is interpreted as a label of the index. This use is not an integer position along the index.).
- A list or array of labels [‘a’, ‘b’, ‘c’] .
- A slice object with labels ‘a’:’f’ (Note that contrary to usual Python slices, both the start and the stop are included, when present in the index! See :ref:`Slicing with labels <indexing.slicing_with_labels>` .
- A boolean array.
- A callable , see :ref:`Selection By Callable <indexing.callable>` .
Note that setting works as well:
With a DataFrame:
Accessing via label slices:
For getting a cross section using a label (equivalent to df.xs(‘a’) ):
For getting values with a boolean array:
NA values in a boolean array propagate as False :
For getting a value explicitly:
Slicing with labels
When using .loc with slices, if both the start and the stop labels are present in the index, then elements located between the two (including them) are returned:
If at least one of the two is absent, but the index is sorted, and can be compared against start and stop labels, then slicing will still work as expected, by selecting labels which rank between the two:
However, if at least one of the two is absent and the index is not sorted, an error will be raised (since doing otherwise would be computationally expensive, as well as potentially ambiguous for mixed type indexes). For instance, in the above example, s.loc[1:6] would raise KeyError .
Also, if the index has duplicate labels and either the start or the stop label is duplicated, an error will be raised. For instance, in the above example, s.loc[2:5] would raise a KeyError .
For more information about duplicate labels, see :ref:`Duplicate Labels <duplicates>` .
Selection by position
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 :ref:`Returning a View versus Copy <indexing.view_versus_copy>` .
pandas provides a suite of methods in order to get purely integer based indexing. The semantics follow closely Python and NumPy slicing. These are 0-based indexing. When slicing, the start bound is included, while the upper bound is excluded. Trying to use a non-integer, even a valid label will raise an IndexError .
The .iloc attribute is the primary access method. The following are valid inputs:
- An integer e.g. 5 .
- A list or array of integers [4, 3, 0] .
- A slice object with ints 1:7 .
- A boolean array.
- A callable , see :ref:`Selection By Callable <indexing.callable>` .
Note that setting works as well:
With a DataFrame:
Select via integer slicing:
Select via integer list:
For getting a cross section using an integer position (equiv to df.xs(1) ):
Out of range slice indexes are handled gracefully just as in Python/NumPy.
Note that using slices that go out of bounds can result in an empty axis (e.g. an empty DataFrame being returned).
A single indexer that is out of bounds will raise an IndexError . A list of indexers where any element is out of bounds will raise an IndexError .
Selection by callable
.loc , .iloc , and also [] indexing can accept a callable as indexer. The callable must be a function with one argument (the calling Series or DataFrame) that returns valid output for indexing.
You can use callable indexing in Series .
Using these methods / indexers, you can chain data selection operations without using a temporary variable.
Combining positional and label-based indexing
If you wish to get the 0th and the 2nd elements from the index in the ‘A’ column, you can do:
This can also be expressed using .iloc , by explicitly getting locations on the indexers, and using positional indexing to select things.
For getting multiple indexers, using .get_indexer :
Indexing with list with missing labels is deprecated
In prior versions, using .loc[list-of-labels] would work as long as at least 1 of the keys was found (otherwise it would raise a KeyError ). This behavior was changed and will now raise a KeyError if at least one label is missing. The recommended alternative is to use .reindex() .
Selection with all keys found is unchanged.
The idiomatic way to achieve selecting potentially not-found elements is via .reindex() . See also the section on :ref:`reindexing <basics.reindexing>` .
Alternatively, if you want to select only valid keys, the following is idiomatic and efficient; it is guaranteed to preserve the dtype of the selection.
Having a duplicated index will raise for a .reindex() :
Generally, you can intersect the desired labels with the current axis, and then reindex.
However, this would still raise if your resulting index is duplicated.
Selecting random samples
A random selection of rows or columns from a Series or DataFrame with the :meth:`
DataFrame.sample` method. The method will sample rows by default, and accepts a specific number of rows/columns to return, or a fraction of rows.
By default, sample will return each row at most once, but one can also sample with replacement using the replace option:
By default, each row has an equal probability of being selected, but if you want rows to have different probabilities, you can pass the sample function sampling weights as weights . These weights can be a list, a NumPy array, or a Series, but they must be of the same length as the object you are sampling. Missing values will be treated as a weight of zero, and inf values are not allowed. If weights do not sum to 1, they will be re-normalized by dividing all weights by the sum of the weights. For example:
When applied to a DataFrame, you can use a column of the DataFrame as sampling weights (provided you are sampling rows and not columns) by simply passing the name of the column as a string.
sample also allows users to sample columns instead of rows using the axis argument.
Finally, one can also set a seed for sample ‘s random number generator using the random_state argument, which will accept either an integer (as a seed) or a NumPy RandomState object.
Setting with enlargement
The .loc/[] operations can perform enlargement when setting a non-existent key for that axis.
In the Series case this is effectively an appending operation.
A DataFrame can be enlarged on either axis via .loc .
This is like an append operation on the DataFrame .
Fast scalar value getting and setting
Since indexing with [] must handle a lot of cases (single-label access, slicing, boolean indexing, etc.), it has a bit of overhead in order to figure out what you’re asking for. If you only want to access a scalar value, the fastest way is to use the at and iat methods, which are implemented on all of the data structures.
Similarly to loc , at provides label based scalar lookups, while, iat provides integer based lookups analogously to iloc
You can also set using these same indexers.
at may enlarge the object in-place as above if the indexer is missing.
Another common operation is the use of boolean vectors to filter the data. The operators are: | for or , & for and , and
for not . These must be grouped by using parentheses, since by default Python will evaluate an expression such as df[‘A’] > 2 & df[‘B’] < 3 as df[‘A’] > (2 & df[‘B’]) < 3 , while the desired evaluation order is (df[‘A’] > 2) & (df[‘B’] < 3) .
Using a boolean vector to index a Series works exactly as in a NumPy ndarray:
You may select rows from a DataFrame using a boolean vector the same length as the DataFrame’s index (for example, something derived from one of the columns of the DataFrame):
List comprehensions and the map method of Series can also be used to produce more complex criteria:
With the choice methods :ref:`Selection by Label <indexing.label>` , :ref:`Selection by Position <indexing.integer>` , and :ref:`Advanced Indexing <advanced>` you may select along more than one axis using boolean vectors combined with other indexing expressions.
iloc supports two kinds of boolean indexing. If the indexer is a boolean Series , an error will be raised. For instance, in the following example, df.iloc[s.values, 1] is ok. The boolean indexer is an array. But df.iloc[s, 1] would raise ValueError .
Indexing with isin
Series.isin` method of Series , which returns a boolean vector that is true wherever the Series elements exist in the passed list. This allows you to select rows where one or more columns have values you want:
The same method is available for Index objects and is useful for the cases when you don’t know which of the sought labels are in fact present:
In addition to that, MultiIndex allows selecting a separate level to use in the membership check:
DataFrame also has an :meth:`
DataFrame.isin` method. When calling isin , pass a set of values as either an array or dict. If values is an array, isin returns a DataFrame of booleans that is the same shape as the original DataFrame, with True wherever the element is in the sequence of values.
Oftentimes you’ll want to match certain values with certain columns. Just make values a dict where the key is the column, and the value is a list of items you want to check for.
To return the DataFrame of booleans where the values are not in the original DataFrame, use the
Combine DataFrame’s isin with the any() and all() methods to quickly select subsets of your data that meet a given criteria. To select a row where each column meets its own criterion:
Selecting values from a Series with a boolean vector generally returns a subset of the data. To guarantee that selection output has the same shape as the original data, you can use the where method in Series and DataFrame .
To return only the selected rows:
To return a Series of the same shape as the original:
Selecting values from a DataFrame with a boolean criterion now also preserves input data shape. where is used under the hood as the implementation. The code below is equivalent to df.where(df < 0) .
In addition, where takes an optional other argument for replacement of values where the condition is False, in the returned copy.
You may wish to set values based on some boolean criteria. This can be done intuitively like so:
where returns a modified copy of the data.
The signature for :func:`DataFrame.where` differs from :func:`numpy.where` . Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2) .
Alignment
Furthermore, where aligns the input boolean condition (ndarray or DataFrame), such that partial selection with setting is possible. This is analogous to partial setting via .loc (but on the contents rather than the axis labels).
Where can also accept axis and level parameters to align the input when performing the where .
This is equivalent to (but faster than) the following.
where can accept a callable as condition and other arguments. The function must be with one argument (the calling Series or DataFrame) and that returns valid output as condition and other argument.
pandas.DataFrame.mask` is the inverse boolean operation of where .
Setting with enlargement conditionally using :func:`numpy`
An alternative to :meth:`
pandas.DataFrame.where` is to use :func:`numpy.where` . Combined with setting a new column, you can use it to enlarge a DataFrame where the values are determined conditionally.
Consider you have two choices to choose from in the following DataFrame. And you want to set a new column color to ‘green’ when the second column has ‘Z’. You can do the following:
If you have multiple conditions, you can use :func:`numpy.select` to achieve that. Say corresponding to three conditions there are three choice of colors, with a fourth color as a fallback, you can do the following.
pandas.DataFrame.query` method that allows selection using an expression.
You can get the value of the frame where column b has values between the values of columns a and c . For example:
Do the same thing but fall back on a named index if there is no column with the name a .
If instead you don’t want to or cannot name your index, you can use the name index in your query expression:
If the name of your index overlaps with a column name, the column name is given precedence. For example,
You can still use the index in a query expression by using the special identifier ‘index’:
If for some reason you have a column named index , then you can refer to the index as ilevel_0 as well, but at this point you should consider renaming your columns to something less ambiguous.
You can also use the levels of a DataFrame with a :class:`
pandas.MultiIndex` as if they were columns in the frame:
If the levels of the MultiIndex are unnamed, you can refer to them using special names:
The convention is ilevel_0 , which means «index level 0» for the 0th level of the index .
pandas.DataFrame.query` is when you have a collection of :class:`
pandas.DataFrame` objects that have a subset of column names (or index levels/names) in common. You can pass the same query to both frames without having to specify which frame you’re interested in querying
pandas.DataFrame.query` Python versus pandas Syntax Comparison
Full numpy-like syntax:
Slightly nicer by removing the parentheses (comparison operators bind tighter than & and | ):
Use English instead of symbols:
Pretty close to how you might write it on paper:
The in and not in operators
pandas.DataFrame.query` also supports special use of Python’s in and not in comparison operators, providing a succinct syntax for calling the isin method of a Series or DataFrame .
You can combine this with other expressions for very succinct queries:
Note that in and not in are evaluated in Python, since numexpr has no equivalent of this operation. However, only the in / not in expression itself is evaluated in vanilla Python. For example, in the expression
(b + c + d) is evaluated by numexpr and then the in operation is evaluated in plain Python. In general, any operations that can be evaluated using numexpr will be.
Special use of the == operator with list objects
Comparing a list of values to a column using == / != works similarly to in / not in .
You can negate boolean expressions with the word not or the
Of course, expressions can be arbitrarily complex too:
DataFrame.query() using numexpr is slightly faster than Python for large frames.
You will only see the performance benefits of using the numexpr engine with DataFrame.query() if your frame has more than approximately 100,000 rows.
This plot was created using a DataFrame with 3 columns each containing floating point values generated using numpy.random.randn() .
If you want to identify and remove duplicate rows in a DataFrame, there are two methods that will help: duplicated and drop_duplicates . Each takes as an argument the columns to use to identify duplicated rows.
- duplicated returns a boolean vector whose length is the number of rows, and which indicates whether a row is duplicated.
- drop_duplicates removes duplicate rows.
By default, the first observed row of a duplicate set is considered unique, but each method has a keep parameter to specify targets to be kept.
- keep=’first’ (default): mark / drop duplicates except for the first occurrence.
- keep=’last’ : mark / drop duplicates except for the last occurrence.
- keep=False : mark / drop all duplicates.
Also, you can pass a list of columns to identify duplications.
To drop duplicates by index value, use Index.duplicated then perform slicing. The same set of options are available for the keep parameter.
Each of Series or DataFrame have a get method which can return a default value.
Looking up values by index/column labels
Sometimes you want to extract a set of values given a sequence of row labels and column labels, this can be achieved by pandas.factorize and NumPy indexing. For instance:
Formerly this could be achieved with the dedicated DataFrame.lookup method which was deprecated in version 1.2.0 and removed in version 2.0.0.
pandas.Index` class and its subclasses can be viewed as implementing an ordered multiset. Duplicates are allowed.
pandas.Index` also provides the infrastructure necessary for lookups, data alignment, and reindexing. The easiest way to create an :class:`
pandas.Index` directly is to pass a list or other sequence to :class:`
or using numbers:
If no dtype is given, Index tries to infer the dtype from the data. It is also possible to give an explicit dtype when instantiating an :class:`Index` :
You can also pass a name to be stored in the index:
The name, if set, will be shown in the console display:
Indexes are «mostly immutable», but it is possible to set and change their name attribute. You can use the rename , set_names to set these attributes directly, and they default to returning a copy.
set_names , set_levels , and set_codes also take an optional level argument
Set operations on Index objects
The two main operations are union and intersection . Difference is provided via the .difference() method.
Also available is the symmetric_difference operation, which returns elements that appear in either idx1 or idx2 , but not in both. This is equivalent to the Index created by idx1.difference(idx2).union(idx2.difference(idx1)) , with duplicates dropped.
The resulting index from a set operation will be sorted in ascending order.
When performing :meth:`Index.union` between indexes with different dtypes, the indexes must be cast to a common dtype. Typically, though not always, this is object dtype. The exception is when performing a union between integer and float data. In this case, the integer values are converted to float
Even though Index can hold missing values ( NaN ), it should be avoided if you do not want any unexpected results. For example, some operations exclude missing values implicitly.
Index.fillna fills missing values with specified scalar value.
Set / reset index
Occasionally you will load or create a data set into a DataFrame and want to add an index after you’ve already done so. There are a couple of different ways.
DataFrame has a :meth:`
DataFrame.set_index` method which takes a column name (for a regular Index ) or a list of column names (for a MultiIndex ). To create a new, re-indexed DataFrame:
The append keyword option allow you to keep the existing index and append the given columns to a MultiIndex:
Other options in set_index allow you not drop the index columns.
Reset the index
As a convenience, there is a new function on DataFrame called :meth:`
DataFrame.reset_index` which transfers the index values into the DataFrame’s columns and sets a simple integer index. This is the inverse operation of :meth:`
The output is more similar to a SQL table or a record array. The names for the columns derived from the index are the ones stored in the names attribute.
You can use the level keyword to remove only a portion of the index:
reset_index takes an optional parameter drop which if true simply discards the index, instead of putting index values in the DataFrame’s columns.
Adding an ad hoc index
If you create an index yourself, you can just assign it to the index field:
Returning a view versus a copy
When setting values in a pandas object, care must be taken to avoid what is called chained indexing . Here is an example.
Compare these two access methods:
These both yield the same results, so which should you use? It is instructive to understand the order of operations on these and why method 2 ( .loc ) is much preferred over method 1 (chained [] ).
dfmi[‘one’] selects the first level of the columns and returns a DataFrame that is singly-indexed. Then another Python operation dfmi_with_one[‘second’] selects the series indexed by ‘second’ . This is indicated by the variable dfmi_with_one because pandas sees these operations as separate events. e.g. separate calls to __getitem__ , so it has to treat them as linear operations, they happen one after another.
Contrast this to df.loc[:,(‘one’,’second’)] which passes a nested tuple of (slice(None),(‘one’,’second’)) to a single call to __getitem__ . This allows pandas to deal with this as a single entity. Furthermore this order of operations can be significantly faster, and allows one to index both axes if so desired.
Why does assignment fail when using chained indexing?
The problem in the previous section is just a performance issue. What’s up with the SettingWithCopy warning? We don’t usually throw warnings around when you do something that might cost a few extra milliseconds!
But it turns out that assigning to the product of chained indexing has inherently unpredictable results. To see this, think about how the Python interpreter executes this code:
But this code is handled differently:
See that __getitem__ in there? Outside of simple cases, it’s very hard to predict whether it will return a view or a copy (it depends on the memory layout of the array, about which pandas makes no guarantees), and therefore whether the __setitem__ will modify dfmi or a temporary object that gets thrown out immediately afterward. That’s what SettingWithCopy is warning you about!
You may be wondering whether we should be concerned about the loc property in the first example. But dfmi.loc is guaranteed to be dfmi itself with modified indexing behavior, so dfmi.loc.__getitem__ / dfmi.loc.__setitem__ operate on dfmi directly. Of course, dfmi.loc.__getitem__(idx) may be a view or a copy of dfmi .
Sometimes a SettingWithCopy warning will arise at times when there’s no obvious chained indexing going on. These are the bugs that SettingWithCopy is designed to catch! pandas is probably trying to warn you that you’ve done this:
Evaluation order matters
When you use chained indexing, the order and type of the indexing operation partially determine whether the result is a slice into the original object, or a copy of the slice.
pandas has the SettingWithCopyWarning because assigning to a copy of a slice is frequently not intentional, but a mistake caused by chained indexing returning a copy where a slice was expected.
If you would like pandas to be more or less trusting about assignment to a chained indexing expression, you can set the :ref:`option <options>` mode.chained_assignment to one of these values:
- ‘warn’ , the default, means a SettingWithCopyWarning is printed.
- ‘raise’ means pandas will raise a SettingWithCopyError you have to deal with.
- None will suppress the warnings entirely.
This however is operating on a copy and will not work.
A chained assignment can also crop up in setting in a mixed dtype frame.
These setting rules apply to all of .loc/.iloc .
The following is the recommended access method using .loc for multiple items (using mask ) and a single item using a fixed index:
The following can work at times, but it is not guaranteed to, and therefore should be avoided:
Last, the subsequent example will not work at all, and so should be avoided:
The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid assignment. There may be false positives; situations where a chained assignment is inadvertently reported.