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>You can use <code>np.where</code> to achieve this:</p>

<pre><code>In [47]:
df = pd.DataFrame(np.random.randn(5,5), columns=list('abcde'))
df

Out[47]:
          a         b         c         d         e
0  0.616829 -0.933365 -0.735308  0.665297 -1.333547
1  0.069158  2.266290 -0.068686 -0.787980 -0.082090
2  1.203311  1.661110 -1.227530 -1.625526  0.045932
3 -0.247134 -1.134400  0.355436  0.787232 -0.474243
4  0.131774  0.349103 -0.632660 -1.549563  1.196455

In [48]:    
df[['a','b','c']] = np.where(df[['a','b','c']] &lt; 0, np.NaN, df[['a','b','c']])
df

Out[48]:
          a         b         c         d         e
0  0.616829       NaN       NaN  0.665297 -1.333547
1  0.069158  2.266290       NaN -0.787980 -0.082090
2  1.203311  1.661110       NaN -1.625526  0.045932
3       NaN       NaN  0.355436  0.787232 -0.474243
4  0.131774  0.349103       NaN -1.549563  1.196455
</code></pre>

python pandas