29

I have a dataframe pd. I would like to change a value of column irr depending on whether it is above or below a thresh hold.

How can I do this in a single line? Now I have

pd['irr'] = pd['irr'][pd['cs']*0.63 > pd['irr']] = 1.0
pd['irr'] = pd['irr'][pd['cs']*0.63 <=  pd['irr']] = 0.0

The problem of course is that I change irr and check it again in the next line.

Is there something like a ternary conditional operator for pandas?

user3142067
  • 1,222
  • 3
  • 13
  • 26
  • Related: [vectorize conditional assignment in pandas dataframe](https://stackoverflow.com/questions/28896769/vectorize-conditional-assignment-in-pandas-dataframe) – ggorlen Jan 28 '23 at 22:00

1 Answers1

38

In pandas no, in numpy yes.

You can use numpy.where or convert boolean Series created by condition to float - Trues are 1.0 and Falses are 0.0:

pd['irr'] = np.where(pd['cs']*0.63 > pd['irr'], 1.0, 0.0)

Or:

pd['irr'] = (pd['cs']*0.63 > pd['irr']).astype(float)

Sample:

pd = pd.DataFrame({'cs':[1,2,5],
                   'irr':[0,100,0.04]})

print (pd)
   cs     irr
0   1    0.00
1   2  100.00
2   5    0.04

pd['irr'] = (pd['cs']*0.63 > pd['irr']).astype(float)
print (pd)
   cs  irr
0   1  1.0
1   2  0.0
2   5  1.0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    You say "pandas no", but it seems like you show how to do it in pandas. Is that only because OP wanted 0/1, and we can convert `bool` to the desired output? But we don't have a true ternary operation in general? – Teepeemm Nov 10 '20 at 15:29
  • Doesn´t this method raise the `SettingWithCopyWarning`? – xicocaio Nov 16 '20 at 19:58