1

I have DataFrame like below:

data = pd.DataFrame({"col1" : ["a", "b", "c"], 
                     "binary" : [0, 1, 0]})

I would like to create and add new column in this DataFrame called "new" where if in column "binary" is 1 then I want to have data from "col1" in my created column "new", but if in "binary" column is 0 then I want to have np.NaN. Below is the result which I really need based on my description and DatFrame above.

enter image description here

Arun Palanisamy
  • 5,281
  • 6
  • 28
  • 53
dingaro
  • 2,156
  • 9
  • 29
  • lots of ways to do this properly, `import numpy as np;df['new'] = np.where(df['binary'].eq(1), df['col1'],np.nan)` – Umar.H Dec 09 '20 at 14:44

1 Answers1

0

you can use where from the numpy package and , and do:

import pandas as pd
import numpy as np
df = pd.DataFrame({"col1" : ["a", "b", "c"], "binary" : [0, 1, 0]})
df['new'] = np.where(df['binary']==1,df['col1'],np.nan)

which prints:

print(df)
  col1  binary  new
0    a       0  NaN
1    b       1    b
2    c       0  NaN
sophocles
  • 13,593
  • 3
  • 14
  • 33