Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
user3142067 Avatar asked Oct 02 '17 12:10

user3142067


People also ask

How do you write 3 conditions in a ternary operator?

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.

How do I assign a value to pandas?

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.

How do I use conditional formatting in pandas?

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 .


1 Answers

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
like image 58
jezrael Avatar answered Sep 23 '22 16:09

jezrael