Pandas: How to conditionally assign multiple columns?

numpy, pandas, python

Solution

I don't think you'll get much simpler than this:

>>> 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)})
>>> 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
>>> df[df[cols] < 0] = np.nan
>>> 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

Problem

I want to replace negative values with `nan` for only certain columns. The simplest way could be: ``` for col in ['a', 'b', 'c']: df.loc[df[col ] < 0, col] = np.nan ``` `df` could have many columns and I only want to do this to specific columns. 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.

Original source