6

I have this df:

data = np.array([[np.nan, 0], [2, 0], [np.nan, 1]])
df = pd.DataFrame(data=data, columns = ['a', 'b'])

which looks like this:

     a    b
    --------
0   NaN  0.0
1   2.0  0.0
2   NaN  1.0

My goal is to create a third column "c" that has a value of 1 when column "a" is equal to NaN and column "b" is equal to 0. "c" would be 0 otherwise. The simple SQL case statement would be:

(CASE WHEN a IS NULL AND b = 0 THEN 1 ELSE 0 END) AS C

The desired output is this:

     a    b   c
    -----------
0   NaN  0.0  1
1   2.0  0.0  0
2   NaN  1.0  0

My (wrong) try:

df['c'] = np.where(df['a']==np.nan & df['b'] == 0, 1, 0)

Many thx.

2
  • What was wrong with your try?
    – Henry
    Commented Jul 5, 2017 at 8:58
  • "cannot compare a dtyped [int64] array with a scalar of type [float]" Commented Jul 5, 2017 at 8:58

4 Answers 4

15

For more control on conditions use np.select. Very similar to case when, can be used to scale up multiple outputs.

df['c'] = np.select(
[
    (df['a'].isnull() & (df['b'] == 0))
], 
[
    1
], 
default=0 )
2
  • Thank you! Whilst other answers give a better answer for the specific question; this is the best answer for a SQL CASE...WHEN equivalent.
    – dsz
    Commented Feb 3, 2020 at 9:43
  • i agree with @dsz this one is the best equivalent for case when statement
    – Osama Lone
    Commented Feb 22, 2021 at 19:31
4

You're almost there, instead use np.where(df['a'].isnull() & (df['b'] == 0), 1, 0) for null check.

Alternatively,

In [258]: df['c'] = (df['a'].isnull() & (df['b'] == 0)).astype(int)

In [259]: df
Out[259]:
     a    b  c
0  NaN  0.0  1
1  2.0  0.0  0
2  NaN  1.0  0
2
  • Thanks John. First statement with np.where is correct. But the alternative seems to be wrong. It gives you c = [1, 1, 0] when it should be [1, 0, 0]. Check it out pls Commented Jul 5, 2017 at 9:06
  • Hey @John Galt, actually 'c' column should have values as [1,0,0]. Commented Jul 5, 2017 at 9:08
3

You cant check series value is NaN using np.nan instead use series.isnull()

Below code gives desired output:

df['c'] = np.where(df['a'].isnull() & np.array(df['b'] == 0),1,0)
1

My personal preference is to use pandas apply function with an if statement:

df['c'] = df.apply(lambda x: (1 if np.isnan(x[0]) and x[1] == 0 else 0), axis=1)
1
  • 1
    I've not tried it, but I suspect that this won't be performant as it's effectively an iteration rather than a vectorised operation.
    – dsz
    Commented Feb 3, 2020 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.