Pandas:用于在 DataFrame 中设置值的三元条件运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46525270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: Ternary conditional operator for setting a value in a DataFrame
提问by user3142067
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.
我有一个数据框pd
。我想irr
根据它是高于还是低于阈值来更改列的值。
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.
问题当然是我irr
在下一行更改并再次检查。
Is there something like a ternary conditional operator for pandas?
有没有像Pandas的三元条件运算符?
回答by jezrael
In pandas no, in numpy yes.
在Pandas中不,在 numpy 中是。
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
:
您可以使用numpy.where
或转换boolean Series
产生的条件float
- True
s为1.0
和False
s为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