Skip to content

Commit c69bc1e

Browse files
committed
mask based multi-index assignment of column values described
1 parent 043b609 commit c69bc1e

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

doc/source/user_guide/indexing.rst

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1870,25 +1870,35 @@ This is the correct access method:
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+
1878+
# Setting multiple items using a mask (recommended)
1879+
mask = dfd['a'].str.startswith('o')
1880+
dfd.loc[mask, 'c'] = 42
1881+
dfd
1882+
1883+
# Setting a single item (recommended)
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)