Skip to content

mask based multi-index assignment of column values described #34461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 2, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions doc/source/user_guide/indexing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1866,29 +1866,39 @@ A chained assignment can also crop up in setting in a mixed dtype frame.

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

This is the correct access method:
The following is the recommended access method using ``.loc`` for multiple items (using ``mask``) and a single item using a fixed index:

.. ipython:: python

dfc = pd.DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]})
dfc.loc[0, 'A'] = 11
dfc
dfc = pd.DataFrame({'a': ['one', 'one', 'two',
'three', 'two', 'one', 'six'],
'c': np.arange(7)})
dfd = dfc.copy()
# Setting multiple items using a mask
mask = dfd['a'].str.startswith('o')
dfd.loc[mask, 'c'] = 42
dfd

# Setting a single item
dfd = dfc.copy()
dfd.loc[2, 'a'] = 11
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you copy first, like L1876.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in de9f6bd

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please resolve at will

dfd

This *can* work at times, but it is not guaranteed to, and therefore should be avoided:
The following *can* work at times, but it is not guaranteed to, and therefore should be avoided:

.. ipython:: python
:okwarning:

dfc = dfc.copy()
dfc['A'][0] = 111
dfc
dfd = dfc.copy()
dfd['a'][2] = 111
dfd

This will **not** work at all, and so should be avoided:
Last, the subsequent example will **not** work at all, and so should be avoided:

::

>>> pd.set_option('mode.chained_assignment','raise')
>>> dfc.loc[0]['A'] = 1111
>>> dfd.loc[0]['a'] = 1111
Traceback (most recent call last)
...
SettingWithCopyException:
Expand Down