Pandas: How to conditionally assign multiple columns?
<p>I want to replace negative values with <code>nan</code> for only certain columns. The simplest way could be:</p>

<pre><code>for col in ['a', 'b', 'c']:
    df.loc[df[col ] &lt; 0, col] = np.nan
</code></pre>

<p><code>df</code> could have many columns and I only want to do this to specific columns. </p>

<p>Is there a way to do this in one line? Seems like this should be easy but I have not been able to figure out.</p>

<p>I don't think you'll get much simpler than this:</p>

<pre><code>&gt;&gt;&gt; df = pd.DataFrame({'a': np.arange(-5, 2), 'b': np.arange(-5, 2), 'c': np.arange(-5, 2), 'd': np.arange(-5, 2), 'e': np.arange(-5, 2)})
&gt;&gt;&gt; df
   a  b  c  d  e
0 -5 -5 -5 -5 -5
1 -4 -4 -4 -4 -4
2 -3 -3 -3 -3 -3
3 -2 -2 -2 -2 -2
4 -1 -1 -1 -1 -1
5  0  0  0  0  0
6  1  1  1  1  1
&gt;&gt;&gt; df[df[cols] &lt; 0] = np.nan
&gt;&gt;&gt; df
     a    b    c  d  e
0  NaN  NaN  NaN -5 -5
1  NaN  NaN  NaN -4 -4
2  NaN  NaN  NaN -3 -3
3  NaN  NaN  NaN -2 -2
4  NaN  NaN  NaN -1 -1
5  0.0  0.0  0.0  0  0
6  1.0  1.0  1.0  1  1
</code></pre>

python pandas