user9238790
user9238790

Reputation:

if statement with condition in python

The idea is the user will be able to extract a certain row under a certain condition. The condition is to return the last 'Pass' encountered before fail. For example, the user inserts the value 5, the if statement should print out 3. As this is the last time he passed. if the user would insert 0, it would also return 3, as this is the last time he passed before he failed.

So basically the idea is to return the last pass encountered before he failed. Another example on the same dataset, if the user passes 7, it would return 7. As this is the last 'pass' before he failed.

---------------------------
#dataSet

Index Result
0      Pass
1      Pass
2      Pass
3      Pass
4      Fail
5      Fail
6      Pass
7      Pass
8      Fail

---------------------------

result = 'Result'
if df.loc[index_value,result] == 'Pass':

else:

Upvotes: 1

Views: 128

Answers (3)

jezrael
jezrael

Reputation: 862541

I think need create lookup Series:

a = df['Result'] == 'Pass'
m = a != a.shift(-1) & a

b = pd.Series(df.index.where(m)).ffill().bfill().astype(int)
print (b)
0    3
1    3
2    3
3    3
4    3
5    3
6    3
7    7
8    7
dtype: int32

val = 7
print(b.loc[val])
7

Upvotes: 1

Fuevo
Fuevo

Reputation: 152

last_pass=0 #set default last pass

result = 'Result'
if df.loc[index_value,result] == 'Pass':
    last_pass = index_value
    return index_value
else:
    return last_pass

Upvotes: 0

shivsn
shivsn

Reputation: 7828

IIUC:

In [125]: user_input = 7

In [126]: if (wd.iloc[user_input]['Result']=='Pass'):
     ...:     value = user_input
     ...:     print(value)
     ...: else:
     ...:     value = (wd[wd.Result=='Pass'].Index - user_input).abs().argmin()
     ...:     print(value)
     ...:     
6

In [124]: wd
Out[124]: 
   Index Result
0      0   Pass
1      1   Pass
2      2   Pass
3      3   Pass
4      4   Fail
5      5   Fail
6      6   Pass
7      7   Fail

Upvotes: 0

Related Questions