Applying condition and update on same column
<p>I have written the following statement to update a column in DataFrame (df)</p>

<pre><code>    score
0   6800
1   7200
2   580
3   6730
</code></pre>

<p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p>

<p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is greater than 999 else keep unchanged. However, i get the following result.</p>

<pre><code>0    680.0
1    720.0
2      NaN
3    673.0
</code></pre>

<p>Also, I want the result as Integers.</p>

<p>my expected output</p>

<pre><code>0    680
1    720
2    580
3    673
</code></pre>

<p><strong>Update</strong></p>

<p>the following worked for me</p>

<pre><code>df["score"] = np.where(df["score"] &gt; 999, df["score"]/10, df["score"]).astype(int)
</code></pre>

<h2>Solution</h2>

<p>Do as in <code>numpy</code>, and use <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">masks</a>:</p>

<pre><code>df['score'][df['score']&gt;999] /= 10
</code></pre>

<p>For legibility you could do:</p>

<pre><code>f = df['score']
f[f&gt;999] /= 10
</code></pre>

<h2>Explanation</h2>

<p><code>df['score']&gt;999</code> will create a mask, a <code>bool</code> array of the same shape as <code>df['score']</code> with <code>True</code>/<code>False</code> values at the positions of the values fulfilling/not fulfilling the given condition. E.g., in the example above:</p>

<pre><code>In [27]: df['score']&gt;999
Out[27]: 
0     True
1     True
2    False
3     True
Name: score, dtype: bool
</code></pre>

<p>You can use this mask to index the array/dataframe directly, to extract only matching elements:</p>

<pre><code>In [28]: df['score'][df['score']&gt;999]
Out[28]: 
0    6800
1    7200
3    6730
Name: score, dtype: int64
</code></pre>

<p>We divide all matching elements by ten and directly assign the result, using <code>/= 10</code>:</p>

<pre><code>In [29]: df['score'][df['score']&gt;999] /= 10

In [30]: df['score']
Out[30]: 
0    680
1    720
2    580
3    673
Name: score, dtype: int64
</code></pre>

python pandas