<commit_before>.. _indexing:

.. currentmodule:: pandas

.. ipython:: python
   :suppress:

   import numpy as np
   import random
   np.random.seed(123456)
   from pandas import *
   import pandas as pd
   randn = np.random.randn
   randint = np.random.randint
   np.set_printoptions(precision=4, suppress=True)
   from pandas.compat import range, zip

***************************
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 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 / chapter, 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. Expect more work to be invested higher-dimensional data
structures (including Panel) in the future, especially in label-based advanced
indexing.

.. note::

   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.

   In addition, whether a copy or a reference is returned for a selection operation, may depend on the context.
   See :ref:`Returning a View versus Copy <indexing.view_versus_copy>`

See the :ref:`cookbook<cookbook.selection>` for some advanced strategies

Choice
------

Starting in 0.11.0, 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 strictly label based, 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!)
  - A boolean array

  See more at :ref:`Selection by Label <indexing.label>`

- ``.iloc`` is strictly integer position based (from ``0`` to ``length-1`` of the axis), will raise ``IndexError`` when the requested indicies are out of bounds. Allowed inputs are:

  - An integer e.g. ``5``
  - A list or array of integers ``[4, 3, 0]``
  - A slice object with ints ``1:7``

  See more at :ref:`Selection by Position <indexing.integer>`

- ``.ix`` supports mixed integer and label based access. It is primarily label based, but will fallback to integer positional access. ``.ix`` is the most general
  and will support any of the inputs to ``.loc`` and ``.iloc``, as well as support for floating point label schemes. ``.ix`` is especially useful when dealing with mixed positional and label
  based hierarchial indexes.

  As using integer slices with ``.ix`` have different behavior depending on whether the slice is interpreted as position based or label based, it's
  usually better to be explicit and use ``.iloc`` or ``.loc``.

  See more at :ref:`Advanced Indexing <indexing.advanced>`, :ref:`Advanced Hierarchical <indexing.advanced_hierarchical>` and :ref:`Fallback Indexing <indexing.fallback>`

Getting values from an object with multi-axes selection uses the following
notation (using ``.loc`` as an example, but applies to ``.iloc`` and ``.ix`` 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 equiv to
``p.loc['a',:,:]``)

.. csv-table::
    :header: "Object Type", "Indexers"
    :widths: 30, 50
    :delim: ;

    Series; ``s.loc[indexer]``
    DataFrame; ``df.loc[row_indexer,column_indexer]``
    Panel; ``p.loc[item_indexer,major_indexer,minor_indexer]``

Deprecations
~~~~~~~~~~~~

Beginning with version 0.11.0, it's recommended that you transition away from
the following methods as they *may* be deprecated in future versions.

  - ``irow``
  - ``icol``
  - ``iget_value``

See the section :ref:`Selection by Position <indexing.integer>` for substitutes.

.. _indexing.basics:

Basics
------

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. Thus,

.. csv-table::
    :header: "Object Type", "Selection", "Return Value Type"
    :widths: 30, 30, 60
    :delim: ;

    Series; ``series[label]``; scalar value
    DataFrame; ``frame[colname]``; ``Series`` corresponding to colname
    Panel; ``panel[itemname]``; ``DataFrame`` corresponing to the itemname

Here we construct a simple time series data set to use for illustrating the
indexing functionality:

.. ipython:: python

   dates = date_range('1/1/2000', periods=8)
   df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
   df
   panel = Panel({'one' : df, 'two' : df - df.mean()})
   panel

.. note::

   None of the indexing functionality is time series specific unless
   specifically stated.

Thus, as per above, we have the most basic indexing using ``[]``:

.. ipython:: python

   s = df['A']
   s[dates[5]]
   panel['two']

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:

.. ipython:: python

   df
   df[['B', 'A']] = df[['A', 'B']]
   df

You may find this useful for applying a transform (in-place) to a subset of the
columns.

Attribute Access
~~~~~~~~~~~~~~~~

.. _indexing.columns.multiple:

.. _indexing.df_cols:

You may access a column on a ``DataFrame``, and a item on a ``Panel`` directly
as an attribute:

.. ipython:: python

   df.A
   panel.one

If you are using the IPython environment, you may also use tab-completion to
see these accessable attributes.

Slicing ranges
~~~~~~~~~~~~~~

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:

.. ipython:: python

   s[:5]
   s[::2]
   s[::-1]

Note that setting works as well:

.. ipython:: python

   s2 = s.copy()
   s2[:5] = 0
   s2

With DataFrame, slicing inside of ``[]`` **slices the rows**. This is provided
largely as a convenience since it is such a common operation.

.. ipython:: python

   df[:3]
   df[::-1]

.. _indexing.label:

Selection By Label
~~~~~~~~~~~~~~~~~~

Pandas provides a suite of methods in order to have **purely label based indexing**. This is a strict inclusion based protocol.
**ALL** of the labels for which you ask, must be in the index or a ``KeyError`` will be raised! When slicing, the start bound is *included*, **AND** the stop bound is *included*. 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!)
- A boolean array

.. ipython:: python

   s1 = Series(np.random.randn(6),index=list('abcdef'))
   s1
   s1.loc['c':]
   s1.loc['b']

Note that setting works as well:

.. ipython:: python

   s1.loc['c':] = 0
   s1

With a DataFrame

.. ipython:: python

   df1 = DataFrame(np.random.randn(6,4),
                   index=list('abcdef'),
                   columns=list('ABCD'))
   df1
   df1.loc[['a','b','d'],:]

Accessing via label slices

.. ipython:: python

   df1.loc['d':,'A':'C']

For getting a cross section using a label (equiv to ``df.xs('a')``)

.. ipython:: python

   df1.loc['a']

For getting values with a boolean array

.. ipython:: python

   df1.loc['a']>0
   df1.loc[:,df1.loc['a']>0]

For getting a value explicity (equiv to deprecated ``df.get_value('a','A')``)

.. ipython:: python

   # this is also equivalent to ``df1.at['a','A']``
   df1.loc['a','A']

.. _indexing.integer:

Selection By Position
~~~~~~~~~~~~~~~~~~~~~

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 bounds is *included*, while the upper bound is *excluded*. Trying to use a non-integer, even a **valid** label will raise a ``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``

.. ipython:: python

   s1 = Series(np.random.randn(5),index=list(range(0,10,2)))
   s1
   s1.iloc[:3]
   s1.iloc[3]

Note that setting works as well:

.. ipython:: python

   s1.iloc[:3] = 0
   s1

With a DataFrame

.. ipython:: python

   df1 = DataFrame(np.random.randn(6,4),
                   index=list(range(0,12,2)),
                   columns=list(range(0,8,2)))
   df1

Select via integer slicing

.. ipython:: python

   df1.iloc[:3]
   df1.iloc[1:5,2:4]

Select via integer list

.. ipython:: python

   df1.iloc[[1,3,5],[1,3]]

For slicing rows explicitly (equiv to deprecated ``df.irow(slice(1,3))``).

.. ipython:: python

   df1.iloc[1:3,:]

For slicing columns explicitly (equiv to deprecated ``df.icol(slice(1,3))``).

.. ipython:: python

   df1.iloc[:,1:3]

For getting a scalar via integer position (equiv to deprecated ``df.get_value(1,1)``)

.. ipython:: python

   # this is also equivalent to ``df1.iat[1,1]``
   df1.iloc[1,1]

For getting a cross section using an integer position (equiv to ``df.xs(1)``)

.. ipython:: python

   df1.iloc[1]

There is one signficant departure from standard python/numpy slicing semantics.
python/numpy allow slicing past the end of an array without an associated error.

.. ipython:: python

    # these are allowed in python/numpy.
    x = list('abcdef')
    x[4:10]
    x[8:10]

Pandas will detect this and raise ``IndexError``, rather than return an empty structure.

::

    >>> df.iloc[:,3:6]
    IndexError: out-of-bounds on slice (end)

.. _indexing.basics.get_value:

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.

Similary to ``loc``, ``at`` provides **label** based scalar lookups, while, ``iat`` provides **integer** based lookups analagously to ``iloc``

.. ipython:: python

   s.iat[5]
   df.at[dates[5], 'A']
   df.iat[3, 0]

You can also set using these same indexers. These have the additional
capability of enlarging an object. This method *always* returns a reference to
the object it modified, which in the case of enlargement, will be a **new object**:

.. ipython:: python

   df.at[dates[5], 'E'] = 7
   df.iat[3, 0] = 7

Boolean indexing
~~~~~~~~~~~~~~~~

.. _indexing.boolean:

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.

Using a boolean vector to index a Series works exactly as in a numpy ndarray:

.. ipython:: python

   s[s > 0]
   s[(s < 0) & (s > -0.5)]
   s[(s < -1) | (s > 1 )]
   s[~(s < 0)]

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):

.. ipython:: python

   df[df['A'] > 0]

Consider the ``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:

.. ipython:: python

   df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : randn(7)})
   df2[df2['a'].isin(['one', 'two'])]

List comprehensions and ``map`` method of Series can also be used to produce
more complex criteria:

.. ipython:: python

   # only want 'two' or 'three'
   criterion = df2['a'].map(lambda x: x.startswith('t'))

   df2[criterion]

   # equivalent but slower
   df2[[x.startswith('t') for x in df2['a']]]

   # Multiple criteria
   df2[criterion & (df2['b'] == 'x')]

Note, with the choice methods :ref:`Selection by Label <indexing.label>`, :ref:`Selection by Position <indexing.integer>`,
and :ref:`Advanced Indexing <indexing.advanced>` you may select along more than one axis using boolean vectors combined with other indexing expressions.

.. ipython:: python

   df2.loc[criterion & (df2['b'] == 'x'),'b':'c']

DataFrame also has an ``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.

.. ipython:: python

   df = DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'],
                'ids2': ['a', 'n', 'c', 'n']})

   values = ['a', 'b', 1, 3]

   df.isin(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.

.. ipython:: python

   values = {'ids': ['a', 'b'], 'vals': [1, 3]}

   df.isin(values)

You can also describe columns using integer location:

.. ipython:: python

   values = {0: ['a', 'b']}

   df.isin(values, iloc=True)


Where and Masking
~~~~~~~~~~~~~~~~~

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

.. ipython:: python

   s[s > 0]

To return a Series of the same shape as the original

.. ipython:: python

   s.where(s > 0)

Selecting values from a DataFrame with a boolean critierion now also preserves
input data shape. ``where`` is used under the hood as the implementation.
Equivalent is ``df.where(df < 0)``

.. ipython:: python
   :suppress:

   dates = date_range('1/1/2000', periods=8)
   df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

.. ipython:: python

   df[df < 0]

In addition, ``where`` takes an optional ``other`` argument for replacement of
values where the condition is False, in the returned copy.

.. ipython:: python

   df.where(df < 0, -df)

You may wish to set values based on some boolean criteria.
This can be done intuitively like so:

.. ipython:: python

   s2 = s.copy()
   s2[s2 < 0] = 0
   s2

   df2 = df.copy()
   df2[df2 < 0] = 0
   df2

Furthermore, ``where`` aligns the input boolean condition (ndarray or DataFrame),
such that partial selection with setting is possible. This is analagous to
partial setting via ``.ix`` (but on the contents rather than the axis labels)

.. ipython:: python

   df2 = df.copy()
   df2[ df2[1:4] > 0 ] = 3
   df2

By default, ``where`` returns a modified copy of the data. There is an
optional parameter ``inplace`` so that the original data can be modified
without creating a copy:

.. ipython:: python

   df_orig = df.copy()

   df_orig.where(df > 0, -df, inplace=True);

   df_orig

``mask`` is the inverse boolean operation of ``where``.

.. ipython:: python

   s.mask(s >= 0)

   df.mask(df >= 0)

Take Methods
~~~~~~~~~~~~

.. _indexing.take:

Similar to numpy ndarrays, pandas Index, Series, and DataFrame also provides
the ``take`` method that retrieves elements along a given axis at the given
indices. The given indices must be either a list or an ndarray of integer
index positions. ``take`` will also accept negative integers as relative positions to the end of the object.

.. ipython:: python

   index = Index(randint(0, 1000, 10))
   index

   positions = [0, 9, 3]

   index[positions]
   index.take(positions)

   ser = Series(randn(10))

   ser.ix[positions]
   ser.take(positions)

For DataFrames, the given indices should be a 1d list or ndarray that specifies
row or column positions.

.. ipython:: python

   frm = DataFrame(randn(5, 3))

   frm.take([1, 4, 3])

   frm.take([0, 2], axis=1)

It is important to note that the ``take`` method on pandas objects are not
intended to work on boolean indices and may return unexpected results.

.. ipython:: python

   arr = randn(10)
   arr.take([False, False, True, True])
   arr[[0, 1]]

   ser = Series(randn(10))
   ser.take([False, False, True, True])
   ser.ix[[0, 1]]

Finally, as a small note on performance, because the ``take`` method handles
a narrower range of inputs, it can offer performance that is a good deal
faster than fancy indexing.

.. ipython::

   arr = randn(10000, 5)
   indexer = np.arange(10000)
   random.shuffle(indexer)

   timeit arr[indexer]
   timeit arr.take(indexer, axis=0)

   ser = Series(arr[:, 0])
   timeit ser.ix[indexer]
   timeit ser.take(indexer)

Duplicate Data
~~~~~~~~~~~~~~

.. _indexing.duplicate:

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 ``take_last`` parameter that indicates the last observed row
should be taken instead.

.. ipython:: python

   df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : np.random.randn(7)})
   df2.duplicated(['a','b'])
   df2.drop_duplicates(['a','b'])
   df2.drop_duplicates(['a','b'], take_last=True)

.. _indexing.dictionarylike:

Dictionary-like ``get`` method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Each of Series, DataFrame, and Panel have a ``get`` method which can return a
default value.

.. ipython:: python

   s = Series([1,2,3], index=['a','b','c'])
   s.get('a')               # equivalent to s['a']
   s.get('x', default=-1)

.. _indexing.advanced:

Advanced Indexing with ``.ix``
------------------------------

.. note::

   The recent addition of ``.loc`` and ``.iloc`` have enabled users to be quite
   explicit about indexing choices. ``.ix`` allows a great flexibility to
   specify indexing locations by *label* and/or *integer position*. Pandas will
   attempt to use any passed *integer* as *label* locations first (like what
   ``.loc`` would do, then to fall back on *positional* indexing, like what
   ``.iloc``  would do). See :ref:`Fallback Indexing <indexing.fallback>` for
   an example.

The syntax of using ``.ix`` is identical to ``.loc``, in :ref:`Selection by
Label <indexing.label>`, and ``.iloc`` in :ref:`Selection by Position <indexing.integer>`.

The ``.ix`` attribute takes the following inputs:

- An integer or single label, e.g. ``5`` or ``'a'``
- A list or array of labels ``['a', 'b', 'c']`` or integers ``[4, 3, 0]``
- A slice object with ints ``1:7`` or labels ``'a':'f'``
- A boolean array

We'll illustrate all of these methods. First, note that this provides a concise
way of reindexing on multiple axes at once:

.. ipython:: python

   subindex = dates[[3,4,5]]
   df.reindex(index=subindex, columns=['C', 'B'])
   df.ix[subindex, ['C', 'B']]

Assignment / setting values is possible when using ``ix``:

.. ipython:: python

   df2 = df.copy()
   df2.ix[subindex, ['C', 'B']] = 0
   df2

Indexing with an array of integers can also be done:

.. ipython:: python

   df.ix[[4,3,1]]
   df.ix[dates[[4,3,1]]]

**Slicing** has standard Python semantics for integer slices:

.. ipython:: python

   df.ix[1:7, :2]

Slicing with labels is semantically slightly different because the slice start
and stop are **inclusive** in the label-based case:

.. ipython:: python

   date1, date2 = dates[[2, 4]]
   print date1, date2
   df.ix[date1:date2]
   df['A'].ix[date1:date2]

Getting and setting rows in a DataFrame, especially by their location, is much
easier:

.. ipython:: python

   df2 = df[:5].copy()
   df2.ix[3]
   df2.ix[3] = np.arange(len(df2.columns))
   df2

Column or row selection can be combined as you would expect with arrays of
labels or even boolean vectors:

.. ipython:: python

   df.ix[df['A'] > 0, 'B']
   df.ix[date1:date2, 'B']
   df.ix[date1, 'B']

Slicing with labels is closely related to the ``truncate`` method which does
precisely ``.ix[start:stop]`` but returns a copy (for legacy reasons).

The ``select`` method
~~~~~~~~~~~~~~~~~~~~~

Another way to extract slices from an object is with the ``select`` method of
Series, DataFrame, and Panel. This method should be used only when there is no
more direct way.  ``select`` takes a function which operates on labels along
``axis`` and returns a boolean.  For instance:

.. ipython:: python

   df.select(lambda x: x == 'A', axis=1)

The ``lookup`` method
~~~~~~~~~~~~~~~~~~~~~

Sometimes you want to extract a set of values given a sequence of row labels
and column labels, and the ``lookup`` method allows for this and returns a
numpy array.  For instance,

.. ipython:: python

  dflookup = DataFrame(np.random.rand(20,4), columns = ['A','B','C','D'])
  dflookup.lookup(list(range(0,10,2)), ['B','C','A','B','D'])

Setting values in mixed-type DataFrame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. _indexing.mixed_type_setting:

Setting values on a mixed-type DataFrame or Panel is supported when using
scalar values, though setting arbitrary vectors is not yet supported:

.. ipython:: python

   df2 = df[:4]
   df2['foo'] = 'bar'
   print df2
   df2.ix[2] = np.nan
   print df2
   print df2.dtypes

.. _indexing.view_versus_copy:

Returning a view versus a copy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The rules about when a view on the data is returned are entirely dependent on
NumPy. Whenever an array of labels or a boolean vector are involved in the
indexing operation, the result will be a copy. With single label / scalar
indexing and slicing, e.g. ``df.ix[3:6]`` or ``df.ix[:, 'A']``, a view will be
returned.

In chained expressions, the order may determine whether a copy is returned or not:

.. ipython:: python


   dfb = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : randn(7)})
   dfb[dfb.a.str.startswith('o')]['c'] = 42  # goes to copy (will be lost)
   dfb['c'][dfb.a.str.startswith('o')] = 42  # passed via reference (will stay)

When assigning values to subsets of your data, thus, make sure to either use the
pandas access methods or explicitly handle the assignment creating a copy.

Fallback indexing
~~~~~~~~~~~~~~~~~~~~

.. _indexing.fallback:

Float indexes should be used only with caution. If you have a float indexed
``DataFrame`` and try to select using an integer, the row that Pandas returns
might not be what you expect. Pandas first attempts to use the *integer*
as a *label* location, but fails to find a match (because the types
are not equal). Pandas then falls back to back to positional indexing.<commit_msg>DOC: bigger badder warnings on chained assignment<commit_after>.. _indexing:

.. currentmodule:: pandas

.. ipython:: python
   :suppress:

   import numpy as np
   import random
   np.random.seed(123456)
   from pandas import *
   import pandas as pd
   randn = np.random.randn
   randint = np.random.randint
   np.set_printoptions(precision=4, suppress=True)
   from pandas.compat import range, zip

***************************
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 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 / chapter, 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. Expect more work to be invested higher-dimensional data
structures (including Panel) in the future, especially in label-based advanced
indexing.

.. note::

   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.

.. warning::

   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:`cookbook<cookbook.selection>` for some advanced strategies

Choice
------

Starting in 0.11.0, 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 strictly label based, 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!)
  - A boolean array

  See more at :ref:`Selection by Label <indexing.label>`

- ``.iloc`` is strictly integer position based (from ``0`` to ``length-1`` of the axis), will raise ``IndexError`` when the requested indicies are out of bounds. Allowed inputs are:

  - An integer e.g. ``5``
  - A list or array of integers ``[4, 3, 0]``
  - A slice object with ints ``1:7``

  See more at :ref:`Selection by Position <indexing.integer>`

- ``.ix`` supports mixed integer and label based access. It is primarily label based, but will fallback to integer positional access. ``.ix`` is the most general
  and will support any of the inputs to ``.loc`` and ``.iloc``, as well as support for floating point label schemes. ``.ix`` is especially useful when dealing with mixed positional and label
  based hierarchial indexes.

  As using integer slices with ``.ix`` have different behavior depending on whether the slice is interpreted as position based or label based, it's
  usually better to be explicit and use ``.iloc`` or ``.loc``.

  See more at :ref:`Advanced Indexing <indexing.advanced>`, :ref:`Advanced Hierarchical <indexing.advanced_hierarchical>` and :ref:`Fallback Indexing <indexing.fallback>`

Getting values from an object with multi-axes selection uses the following
notation (using ``.loc`` as an example, but applies to ``.iloc`` and ``.ix`` 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 equiv to
``p.loc['a',:,:]``)

.. csv-table::
    :header: "Object Type", "Indexers"
    :widths: 30, 50
    :delim: ;

    Series; ``s.loc[indexer]``
    DataFrame; ``df.loc[row_indexer,column_indexer]``
    Panel; ``p.loc[item_indexer,major_indexer,minor_indexer]``

Deprecations
~~~~~~~~~~~~

Beginning with version 0.11.0, it's recommended that you transition away from
the following methods as they *may* be deprecated in future versions.

  - ``irow``
  - ``icol``
  - ``iget_value``

See the section :ref:`Selection by Position <indexing.integer>` for substitutes.

.. _indexing.basics:

Basics
------

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. Thus,

.. csv-table::
    :header: "Object Type", "Selection", "Return Value Type"
    :widths: 30, 30, 60
    :delim: ;

    Series; ``series[label]``; scalar value
    DataFrame; ``frame[colname]``; ``Series`` corresponding to colname
    Panel; ``panel[itemname]``; ``DataFrame`` corresponing to the itemname

Here we construct a simple time series data set to use for illustrating the
indexing functionality:

.. ipython:: python

   dates = date_range('1/1/2000', periods=8)
   df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
   df
   panel = Panel({'one' : df, 'two' : df - df.mean()})
   panel

.. note::

   None of the indexing functionality is time series specific unless
   specifically stated.

Thus, as per above, we have the most basic indexing using ``[]``:

.. ipython:: python

   s = df['A']
   s[dates[5]]
   panel['two']

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:

.. ipython:: python

   df
   df[['B', 'A']] = df[['A', 'B']]
   df

You may find this useful for applying a transform (in-place) to a subset of the
columns.

Attribute Access
~~~~~~~~~~~~~~~~

.. _indexing.columns.multiple:

.. _indexing.df_cols:

You may access a column on a ``DataFrame``, and a item on a ``Panel`` directly
as an attribute:

.. ipython:: python

   df.A
   panel.one

If you are using the IPython environment, you may also use tab-completion to
see these accessable attributes.

Slicing ranges
~~~~~~~~~~~~~~

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:

.. ipython:: python

   s[:5]
   s[::2]
   s[::-1]

Note that setting works as well:

.. ipython:: python

   s2 = s.copy()
   s2[:5] = 0
   s2

With DataFrame, slicing inside of ``[]`` **slices the rows**. This is provided
largely as a convenience since it is such a common operation.

.. ipython:: python

   df[:3]
   df[::-1]

.. _indexing.label:

Selection By Label
~~~~~~~~~~~~~~~~~~

.. warning::

   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 have **purely label based indexing**. This is a strict inclusion based protocol.
**ALL** of the labels for which you ask, must be in the index or a ``KeyError`` will be raised! When slicing, the start bound is *included*, **AND** the stop bound is *included*. 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!)
- A boolean array

.. ipython:: python

   s1 = Series(np.random.randn(6),index=list('abcdef'))
   s1
   s1.loc['c':]
   s1.loc['b']

Note that setting works as well:

.. ipython:: python

   s1.loc['c':] = 0
   s1

With a DataFrame

.. ipython:: python

   df1 = DataFrame(np.random.randn(6,4),
                   index=list('abcdef'),
                   columns=list('ABCD'))
   df1
   df1.loc[['a','b','d'],:]

Accessing via label slices

.. ipython:: python

   df1.loc['d':,'A':'C']

For getting a cross section using a label (equiv to ``df.xs('a')``)

.. ipython:: python

   df1.loc['a']

For getting values with a boolean array

.. ipython:: python

   df1.loc['a']>0
   df1.loc[:,df1.loc['a']>0]

For getting a value explicity (equiv to deprecated ``df.get_value('a','A')``)

.. ipython:: python

   # this is also equivalent to ``df1.at['a','A']``
   df1.loc['a','A']

.. _indexing.integer:

Selection By Position
~~~~~~~~~~~~~~~~~~~~~

.. warning::

   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 bounds is *included*, while the upper bound is *excluded*. Trying to use a non-integer, even a **valid** label will raise a ``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``

.. ipython:: python

   s1 = Series(np.random.randn(5),index=list(range(0,10,2)))
   s1
   s1.iloc[:3]
   s1.iloc[3]

Note that setting works as well:

.. ipython:: python

   s1.iloc[:3] = 0
   s1

With a DataFrame

.. ipython:: python

   df1 = DataFrame(np.random.randn(6,4),
                   index=list(range(0,12,2)),
                   columns=list(range(0,8,2)))
   df1

Select via integer slicing

.. ipython:: python

   df1.iloc[:3]
   df1.iloc[1:5,2:4]

Select via integer list

.. ipython:: python

   df1.iloc[[1,3,5],[1,3]]

For slicing rows explicitly (equiv to deprecated ``df.irow(slice(1,3))``).

.. ipython:: python

   df1.iloc[1:3,:]

For slicing columns explicitly (equiv to deprecated ``df.icol(slice(1,3))``).

.. ipython:: python

   df1.iloc[:,1:3]

For getting a scalar via integer position (equiv to deprecated ``df.get_value(1,1)``)

.. ipython:: python

   # this is also equivalent to ``df1.iat[1,1]``
   df1.iloc[1,1]

For getting a cross section using an integer position (equiv to ``df.xs(1)``)

.. ipython:: python

   df1.iloc[1]

There is one signficant departure from standard python/numpy slicing semantics.
python/numpy allow slicing past the end of an array without an associated error.

.. ipython:: python

    # these are allowed in python/numpy.
    x = list('abcdef')
    x[4:10]
    x[8:10]

Pandas will detect this and raise ``IndexError``, rather than return an empty structure.

::

    >>> df.iloc[:,3:6]
    IndexError: out-of-bounds on slice (end)

.. _indexing.basics.get_value:

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.

Similary to ``loc``, ``at`` provides **label** based scalar lookups, while, ``iat`` provides **integer** based lookups analagously to ``iloc``

.. ipython:: python

   s.iat[5]
   df.at[dates[5], 'A']
   df.iat[3, 0]

You can also set using these same indexers. These have the additional
capability of enlarging an object. This method *always* returns a reference to
the object it modified, which in the case of enlargement, will be a **new object**:

.. ipython:: python

   df.at[dates[5], 'E'] = 7
   df.iat[3, 0] = 7

Boolean indexing
~~~~~~~~~~~~~~~~

.. _indexing.boolean:

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.

Using a boolean vector to index a Series works exactly as in a numpy ndarray:

.. ipython:: python

   s[s > 0]
   s[(s < 0) & (s > -0.5)]
   s[(s < -1) | (s > 1 )]
   s[~(s < 0)]

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):

.. ipython:: python

   df[df['A'] > 0]

Consider the ``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:

.. ipython:: python

   df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : randn(7)})
   df2[df2['a'].isin(['one', 'two'])]

List comprehensions and ``map`` method of Series can also be used to produce
more complex criteria:

.. ipython:: python

   # only want 'two' or 'three'
   criterion = df2['a'].map(lambda x: x.startswith('t'))

   df2[criterion]

   # equivalent but slower
   df2[[x.startswith('t') for x in df2['a']]]

   # Multiple criteria
   df2[criterion & (df2['b'] == 'x')]

Note, with the choice methods :ref:`Selection by Label <indexing.label>`, :ref:`Selection by Position <indexing.integer>`,
and :ref:`Advanced Indexing <indexing.advanced>` you may select along more than one axis using boolean vectors combined with other indexing expressions.

.. ipython:: python

   df2.loc[criterion & (df2['b'] == 'x'),'b':'c']

DataFrame also has an ``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.

.. ipython:: python

   df = DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'],
                'ids2': ['a', 'n', 'c', 'n']})

   values = ['a', 'b', 1, 3]

   df.isin(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.

.. ipython:: python

   values = {'ids': ['a', 'b'], 'vals': [1, 3]}

   df.isin(values)

You can also describe columns using integer location:

.. ipython:: python

   values = {0: ['a', 'b']}

   df.isin(values, iloc=True)


Where and Masking
~~~~~~~~~~~~~~~~~

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

.. ipython:: python

   s[s > 0]

To return a Series of the same shape as the original

.. ipython:: python

   s.where(s > 0)

Selecting values from a DataFrame with a boolean critierion now also preserves
input data shape. ``where`` is used under the hood as the implementation.
Equivalent is ``df.where(df < 0)``

.. ipython:: python
   :suppress:

   dates = date_range('1/1/2000', periods=8)
   df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

.. ipython:: python

   df[df < 0]

In addition, ``where`` takes an optional ``other`` argument for replacement of
values where the condition is False, in the returned copy.

.. ipython:: python

   df.where(df < 0, -df)

You may wish to set values based on some boolean criteria.
This can be done intuitively like so:

.. ipython:: python

   s2 = s.copy()
   s2[s2 < 0] = 0
   s2

   df2 = df.copy()
   df2[df2 < 0] = 0
   df2

Furthermore, ``where`` aligns the input boolean condition (ndarray or DataFrame),
such that partial selection with setting is possible. This is analagous to
partial setting via ``.ix`` (but on the contents rather than the axis labels)

.. ipython:: python

   df2 = df.copy()
   df2[ df2[1:4] > 0 ] = 3
   df2

By default, ``where`` returns a modified copy of the data. There is an
optional parameter ``inplace`` so that the original data can be modified
without creating a copy:

.. ipython:: python

   df_orig = df.copy()

   df_orig.where(df > 0, -df, inplace=True);

   df_orig

``mask`` is the inverse boolean operation of ``where``.

.. ipython:: python

   s.mask(s >= 0)

   df.mask(df >= 0)

Take Methods
~~~~~~~~~~~~

.. _indexing.take:

Similar to numpy ndarrays, pandas Index, Series, and DataFrame also provides
the ``take`` method that retrieves elements along a given axis at the given
indices. The given indices must be either a list or an ndarray of integer
index positions. ``take`` will also accept negative integers as relative positions to the end of the object.

.. ipython:: python

   index = Index(randint(0, 1000, 10))
   index

   positions = [0, 9, 3]

   index[positions]
   index.take(positions)

   ser = Series(randn(10))

   ser.ix[positions]
   ser.take(positions)

For DataFrames, the given indices should be a 1d list or ndarray that specifies
row or column positions.

.. ipython:: python

   frm = DataFrame(randn(5, 3))

   frm.take([1, 4, 3])

   frm.take([0, 2], axis=1)

It is important to note that the ``take`` method on pandas objects are not
intended to work on boolean indices and may return unexpected results.

.. ipython:: python

   arr = randn(10)
   arr.take([False, False, True, True])
   arr[[0, 1]]

   ser = Series(randn(10))
   ser.take([False, False, True, True])
   ser.ix[[0, 1]]

Finally, as a small note on performance, because the ``take`` method handles
a narrower range of inputs, it can offer performance that is a good deal
faster than fancy indexing.

.. ipython::

   arr = randn(10000, 5)
   indexer = np.arange(10000)
   random.shuffle(indexer)

   timeit arr[indexer]
   timeit arr.take(indexer, axis=0)

   ser = Series(arr[:, 0])
   timeit ser.ix[indexer]
   timeit ser.take(indexer)

Duplicate Data
~~~~~~~~~~~~~~

.. _indexing.duplicate:

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 ``take_last`` parameter that indicates the last observed row
should be taken instead.

.. ipython:: python

   df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                    'c' : np.random.randn(7)})
   df2.duplicated(['a','b'])
   df2.drop_duplicates(['a','b'])
   df2.drop_duplicates(['a','b'], take_last=True)

.. _indexing.dictionarylike:

Dictionary-like ``get`` method
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Each of Series, DataFrame, and Panel have a ``get`` method which can return a
default value.

.. ipython:: python

   s = Series([1,2,3], index=['a','b','c'])
   s.get('a')               # equivalent to s['a']
   s.get('x', default=-1)

.. _indexing.advanced:

Advanced Indexing with ``.ix``
------------------------------

.. note::

   The recent addition of ``.loc`` and ``.iloc`` have enabled users to be quite
   explicit about indexing choices. ``.ix`` allows a great flexibility to
   specify indexing locations by *label* and/or *integer position*. Pandas will
   attempt to use any passed *integer* as *label* locations first (like what
   ``.loc`` would do, then to fall back on *positional* indexing, like what
   ``.iloc``  would do). See :ref:`Fallback Indexing <indexing.fallback>` for
   an example.

The syntax of using ``.ix`` is identical to ``.loc``, in :ref:`Selection by
Label <indexing.label>`, and ``.iloc`` in :ref:`Selection by Position <indexing.integer>`.

The ``.ix`` attribute takes the following inputs:

- An integer or single label, e.g. ``5`` or ``'a'``
- A list or array of labels ``['a', 'b', 'c']`` or integers ``[4, 3, 0]``
- A slice object with ints ``1:7`` or labels ``'a':'f'``
- A boolean array

We'll illustrate all of these methods. First, note that this provides a concise
way of reindexing on multiple axes at once:

.. ipython:: python

   subindex = dates[[3,4,5]]
   df.reindex(index=subindex, columns=['C', 'B'])
   df.ix[subindex, ['C', 'B']]

Assignment / setting values is possible when using ``ix``:

.. ipython:: python

   df2 = df.copy()
   df2.ix[subindex, ['C', 'B']] = 0
   df2

Indexing with an array of integers can also be done:

.. ipython:: python

   df.ix[[4,3,1]]
   df.ix[dates[[4,3,1]]]

**Slicing** has standard Python semantics for integer slices:

.. ipython:: python

   df.ix[1:7, :2]

Slicing with labels is semantically slightly different because the slice start
and stop are **inclusive** in the label-based case:

.. ipython:: python

   date1, date2 = dates[[2, 4]]
   print date1, date2
   df.ix[date1:date2]
   df['A'].ix[date1:date2]

Getting and setting rows in a DataFrame, especially by their location, is much
easier:

.. ipython:: python

   df2 = df[:5].copy()
   df2.ix[3]
   df2.ix[3] = np.arange(len(df2.columns))
   df2

Column or row selection can be combined as you would expect with arrays of
labels or even boolean vectors:

.. ipython:: python

   df.ix[df['A'] > 0, 'B']
   df.ix[date1:date2, 'B']
   df.ix[date1, 'B']

Slicing with labels is closely related to the ``truncate`` method which does
precisely ``.ix[start:stop]`` but returns a copy (for legacy reasons).

The ``select`` method
~~~~~~~~~~~~~~~~~~~~~

Another way to extract slices from an object is with the ``select`` method of
Series, DataFrame, and Panel. This method should be used only when there is no
more direct way.  ``select`` takes a function which operates on labels along
``axis`` and returns a boolean.  For instance:

.. ipython:: python

   df.select(lambda x: x == 'A', axis=1)

The ``lookup`` method
~~~~~~~~~~~~~~~~~~~~~

Sometimes you want to extract a set of values given a sequence of row labels
and column labels, and the ``lookup`` method allows for this and returns a
numpy array.  For instance,

.. ipython:: python

  dflookup = DataFrame(np.random.rand(20,4), columns = ['A','B','C','D'])
  dflookup.lookup(list(range(0,10,2)), ['B','C','A','B','D'])

Setting values in mixed-type DataFrame
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. _indexing.mixed_type_setting:

Setting values on a mixed-type DataFrame or Panel is supported when using
scalar values, though setting arbitrary vectors is not yet supported:

.. ipython:: python

   df2 = df[:4]
   df2['foo'] = 'bar'
   print df2
   df2.ix[2] = np.nan
   print df2
   print df2.dtypes

.. _indexing.view_versus_copy:

Returning a view versus a copy
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The rules about when a view on the data is returned are entirely dependent on
NumPy. Whenever an array of labels or a boolean vector are involved in the
indexing operation, the result will be a copy. With single label / scalar
indexing and slicing, e.g. ``df.ix[3:6]`` or ``df.ix[:, 'A']``, a view will be
returned.

In chained expressions, the order may determine whether a copy is returned or not:

.. ipython:: python


   dfb = DataFrame({'a' : ['one', 'one', 'two',
                           'three', 'two', 'one', 'six'],
                    'b' : ['x', 'y', 'y',
                           'x', 'y', 'x', 'x'],
                    'c' : randn(7)})


   # goes to copy (will be lost)
   dfb[dfb.a.str.startswith('o')]['c'] = 42

   # passed via reference (will stay)
   dfb['c'][dfb.a.str.startswith('o')] = 42

A chained assignment can also crop up in setting in a mixed dtype frame.

.. note::

   These setting rules apply to all of ``.loc/.iloc/.ix``

This is the correct access method

.. ipython:: python

   dfc = DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})
   dfc_copy = dfc.copy()
   dfc_copy.loc[0,'A'] = 11
   dfc_copy

This *can* work at times, but is not guaranteed, and so should be avoided

.. ipython:: python

   dfc_copy = dfc.copy()
   dfc_copy['A'][0] = 111
   dfc_copy

This will **not** work at all, and so should be avoided

.. ipython:: python

   dfc_copy = dfc.copy()
   dfc_copy.loc[0]['A'] = 1111
   dfc_copy

When assigning values to subsets of your data, thus, make sure to either use the
pandas access methods or explicitly handle the assignment creating a copy.

Fallback indexing
~~~~~~~~~~~~~~~~~~~~

.. _indexing.fallback:

Float indexes should be used only with caution. If you have a float indexed
``DataFrame`` and try to select using an integer, the row that Pandas returns
might not be what you expect. Pandas first attempts to use the *integer*
as a *label* location, but fails to find a match (because the types
are not equal). Pandas then falls back to back to positional indexing.
{'fraction_non_alphanumeric': 0.14105416527200773, 'fraction_numerical': 0.013999094292071117, 'mean_word_length': 3.6515248649143692, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6114442', 'n_tokens_mistral': 16394, 'n_tokens_neox': 15561, 'n_words': 6609}