Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

python - Pandas: Ternary conditional operator for setting a value in a DataFrame

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...