expected result table
A cond expect
0 0.12 FALSE
1 0.38 TRUE
2 0.93 FALSE
3 0.42 FALSE
4 0.18 TRUE
5 0.86 FALSE 0.38
6 0.43 FALSE 0.38
7 0.99 TRUE
8 0.84 FALSE 0.18
9 0.65 FALSE 0.18
I want to get the value of ‘A’ column when the ‘cond’ column is true
But what I want is the value of the 2nd true above
CodePudding user response:
We can do where with your cond , then get the value for all True after dropna
then we shift
the value and reindex
back with ffill
df.loc[~df['cond'],'expect'] = df['A'].where(df['cond']).dropna().shift().reindex(df.index).ffill()
df
Out[183]:
A cond expect
0 0.12 False NaN
1 0.38 True NaN
2 0.93 False NaN
3 0.42 False NaN
4 0.18 True NaN
5 0.86 False 0.38
6 0.43 False 0.38
7 0.99 True NaN
8 0.84 False 0.18
9 0.65 False 0.18
CodePudding user response:
If you want to ALWAYS obtain the value of the 2nd TRUE:
count = 1
val2 = 0
# Iterate over panda Data Frame
for index, row in df.iterrows():
if row['cond'] == 'TRUE':
# Get the Second TRUE value
if count == 2:
val2 = row['A']
break
count = 1