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?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.
One way to conditionally format your Pandas DataFrame is to highlight cells which meet certain conditions. To do so, we can write a simple function and pass that function into the Styler object using . apply() or .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With