Pandas:用于在DataFrame中设置值的三元条件运算符 [英] Pandas: Ternary conditional operator for setting a value in a DataFrame
本文介绍了Pandas:用于在DataFrame中设置值的三元条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框pd
.我想更改列irr
的值,具体取决于它是高于还是低于脱粒保持力.
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
当然,问题是我更改了irr
并在下一行中再次进行了检查.
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?
推荐答案
在熊猫中不,在numpy中是.
In pandas no, in numpy yes.
您可以使用 numpy.where
或进行转换由float
的条件创建的boolean Series
-True
是1.0
,而False
是0.0
:
You can use numpy.where
or convert boolean Series
created by condition to float
- True
s are 1.0
and False
s are 0.0
:
pd['irr'] = np.where(pd['cs']*0.63 > pd['irr'], 1.0, 0.0)
或者:
pd['irr'] = (pd['cs']*0.63 > pd['irr']).astype(float)
示例:
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
这篇关于Pandas:用于在DataFrame中设置值的三元条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文