Skip to content

Commit 5703477

Browse files
authored
mask based multi-index assignment of column values described (#34461)
1 parent b405904 commit 5703477

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

doc/source/user_guide/indexing.rst

+20-10
Original file line numberDiff line numberDiff line change
@@ -1866,29 +1866,39 @@ A chained assignment can also crop up in setting in a mixed dtype frame.
18661866

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

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

18711871
.. ipython:: python
18721872
1873-
dfc = pd.DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]})
1874-
dfc.loc[0, 'A'] = 11
1875-
dfc
1873+
dfc = pd.DataFrame({'a': ['one', 'one', 'two',
1874+
'three', 'two', 'one', 'six'],
1875+
'c': np.arange(7)})
1876+
dfd = dfc.copy()
1877+
# Setting multiple items using a mask
1878+
mask = dfd['a'].str.startswith('o')
1879+
dfd.loc[mask, 'c'] = 42
1880+
dfd
1881+
1882+
# Setting a single item
1883+
dfd = dfc.copy()
1884+
dfd.loc[2, 'a'] = 11
1885+
dfd
18761886
1877-
This *can* work at times, but it is not guaranteed to, and therefore should be avoided:
1887+
The following *can* work at times, but it is not guaranteed to, and therefore should be avoided:
18781888

18791889
.. ipython:: python
18801890
:okwarning:
18811891
1882-
dfc = dfc.copy()
1883-
dfc['A'][0] = 111
1884-
dfc
1892+
dfd = dfc.copy()
1893+
dfd['a'][2] = 111
1894+
dfd
18851895
1886-
This will **not** work at all, and so should be avoided:
1896+
Last, the subsequent example will **not** work at all, and so should be avoided:
18871897

18881898
::
18891899

18901900
>>> pd.set_option('mode.chained_assignment','raise')
1891-
>>> dfc.loc[0]['A'] = 1111
1901+
>>> dfd.loc[0]['a'] = 1111
18921902
Traceback (most recent call last)
18931903
...
18941904
SettingWithCopyException:

0 commit comments

Comments
 (0)