Pandas: Ternary conditional operator for setting a value in a DataFrame
14,240
In pandas no, in numpy yes.
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)
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
Related videos on Youtube
Author by
user3142067
Updated on September 24, 2022Comments
-
user3142067 over 1 year
I have a dataframe
pd
. I would like to change a value of columnirr
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?
-
Teepeemm over 3 yearsYou 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? -
xicocaio over 3 yearsDoesn´t this method raise the
SettingWithCopyWarning
?