@@ -1866,29 +1866,39 @@ A chained assignment can also crop up in setting in a mixed dtype frame.
1866
1866
1867
1867
These setting rules apply to all of ``.loc/.iloc ``.
1868
1868
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 :
1870
1870
1871
1871
.. ipython :: python
1872
1872
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
1876
1886
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:
1878
1888
1879
1889
.. ipython :: python
1880
1890
:okwarning:
1881
1891
1882
- dfc = dfc.copy()
1883
- dfc[ ' A ' ][0 ] = 111
1884
- dfc
1892
+ dfd = dfc.copy()
1893
+ dfd[ ' a ' ][2 ] = 111
1894
+ dfd
1885
1895
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:
1887
1897
1888
1898
::
1889
1899
1890
1900
>>> pd.set_option('mode.chained_assignment','raise')
1891
- >>> dfc .loc[0]['A '] = 1111
1901
+ >>> dfd .loc[0]['a '] = 1111
1892
1902
Traceback (most recent call last)
1893
1903
...
1894
1904
SettingWithCopyException:
0 commit comments