Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...