Pandas: Change values chosen by boolean indexing in a column without getting a warning
<p>I have a dataframe, I want to change only those values of a column where another column fulfills a certain condition. I'm trying to do this with <code>iloc</code> at the moment and it either does not work or I'm getting that annoying warning:</p>

<blockquote>
  <p>A value is trying to be set on a copy of a slice from a DataFrame</p>
</blockquote>

<p>Example:</p>

<pre><code>import pandas as pd
DF = pd.DataFrame({'A':[1,1,2,1,2,2,1,2,1],'B':['a','a','b','c','x','t','i','x','b']})
</code></pre>

<p>Doing one of those</p>

<pre><code>DF['B'].iloc[:][DF['A'] == 1] = 'X'

DF.iloc[:]['B'][DF['A'] == 1] = 'Y'
</code></pre>

<p>works, but leads to the warning above.</p>

<p>This one also gives a warning, but does not work:</p>

<pre><code>DF.iloc[:][DF['A'] == 1]['B'] = 'Z'
</code></pre>

<p>I'm really confused about how to do boolean indexing using <code>loc</code>, <code>iloc</code>, and <code>ix</code> right, that is, how to provide row index, column index, AND boolean index in the right order and with the correct syntax. </p>

<p>Can someone clear this up for me?</p>

<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>:</p>

<pre><code>import pandas as pd
DF = pd.DataFrame({'A':[1,1,2,1,2,2,1,2,1],'B':['a','a','b','c','x','t','i','x','b']})


DF.ix[DF['A'] == 1, 'B'] = 'X'
print (DF)

0  1  X
1  1  X
2  2  b
3  1  X
4  2  x
5  2  t
6  1  X
7  2  x
8  1  X
</code></pre>

<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a>:</p>

<pre><code>DF.B = DF.B.mask(DF['A'] == 1, 'X')
print (DF)
   A  B
0  1  X
1  1  X
2  2  b
3  1  X
4  2  x
5  2  t
6  1  X
7  2  x
8  1  X
</code></pre>

<p>Nice article about <a href="http://tomaugspurger.github.io/modern-1.html" rel="nofollow"><code>SettingWithCopy</code> by Tom Augspurger</a>.</p>

python python-2.7 pandas indexing condition