Equivalent to the numpy where function in pandas

Viewed 131

Here is my problem, I have two columns as below :

 A   B
-3   4
-6  -8
12  14

I would like to create a code that replace all the values by 1 if the value is > -2 and by 0 if not.

I know that with numpy it would have been simple by using d["newcolum"]=np.where(d < -2,1,0) but I have more difficulties with pandas as its where function just show the value if the condition is not met.

Do you guys know something that could help me? Thanks

1 Answers

If want set 0 and 1 values convert boolean mask to integer:

df = (df < -2).astype(int)
print (df)
   A  B
0  1  0
1  1  1
2  0  0

Using np.where ia absolutely fine, only need DataFrame constructor:

df = pd.DataFrame(np.where(df < -2,1,0), index=df.index, columns=df.columns)
print (df)
   A  B
0  1  0
1  1  1
2  0  0
Related