Replacing values in a column for a subset of rows
<p>I have a <code>dataframe</code> having multiple columns. I would like to replace the value in a column called <code>Discriminant</code>. Now this value needs to only be replaced for a few rows, whenever a condition is met in another column called <code>ids</code>. I tried various methods; The most common method seems to be using the <code>.loc</code> method, but for some reason it doesn't work for me. </p>

<p>Here are the variations that I am unsuccessfully trying:</p>

<p><code>encodedid</code> - variable used for condition checking</p>

<p><code>indices</code> - variable used for subsetting the <code>dataframe</code> (starts from zero)</p>

<p><strong>Variation 1:</strong></p>

<pre><code>df[df.ids == encodedid].loc[df.ids==encodedid, 'Discriminant'].values[indices] = 'Y'
</code></pre>

<p><strong>Variation 2:</strong></p>

<pre><code>df[df['ids'] == encodedid].iloc[indices,:].set_value('questionid','Discriminant', 'Y')
</code></pre>

<p><strong>Variation 3:</strong></p>

<pre><code>df.loc[df.ids==encodedid, 'Discriminant'][indices] = 'Y'
</code></pre>

<p><code>Variation 3</code> particularly has been disappointing in that most posts on SO tend to say it should work but it gives me the following error:</p>

<pre><code>ValueError: [ 0  1  2  3  5  6  7  8 10 11 12 13 14 16 17 18 19 20 21 22 23] not contained in the index
</code></pre>

<p>Any pointers will be highly appreciated.</p>

<p>you are slicing too much. try something like this:</p>

<pre><code>indexer = df[df.ids == encodedid].index
df.loc[indexer, 'Discriminant'] = 'Y'
</code></pre>

<p><code>.loc[]</code> needs an index list and a column list. you can set the value of that slice easily using <code>=</code> 'what you need'</p>

<p>looking at your problem you might want to set that for 2 columns at the same time such has:</p>

<pre><code>indexer = df[df.ids == encodedid].index
column_list = ['Discriminant', 'questionid']

df.loc[indexer, column_list] = 'Y'
</code></pre>

python pandas dataframe