3

Here is a sample data. Whenever I see a Not win or Not fail in Event column, I want to change the value in row-1 of Time column to 0.

x = pd.DataFrame({'Id': [102,303,944, 111, 675, 236], 'Event':['win', 'fail','Not fail','win','win','Not win'],
               'Time':[10,22,0, 23, 45, 0]})

This is how the outcome should look.

        Event       Id   Time
0       win         102  10
1       fail        303  0
2       Not fail    944  0
3       win         111  23
4       win         675  0
5       Not win     236  0
jpp
  • 159,742
  • 34
  • 281
  • 339
A.Abs
  • 460
  • 4
  • 19

4 Answers4

3

try this,

l=['Not win','Not fail']
mask=df['Event'].isin(l).shift(-1).fillna(False)
df.loc[mask,'Time']=0

Output:

      Event   Id  Time
0       win  102    10
1      fail  303     0
2  Not fail  944     0
3       win  111    23
4       win  675     0
5   Not win  236     0
Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111
1
x["isPreviousEventNotFailNotWin"] = ((x.Event == "Not fail") | (x.Event == "Not win")).shift(-1)
x.Time[x.isPreviousEventNotFailNotWin == True] = 0
Charles R
  • 1,621
  • 1
  • 8
  • 25
1

You can use where in this way:

l = ['Not fail', 'Not win']
x['Time'] = np.where(x['Event'].shift(-1).isin(l), 0, x['Time'])

Output:

      Event   Id  Time
0       win  102    10
1      fail  303     0
2  Not fail  944     0
3       win  111    23
4       win  675     0
5   Not win  236     0
Joe
  • 12,057
  • 5
  • 39
  • 55
1

Using a Boolean mask with pd.Series.shift, followed by pd.DataFrame.loc:

mask = x['Event'].isin(['Not fail', 'Not win']).shift(-1).fillna(False)

x.loc[mask, 'Time'] = 0

print(x)

      Event   Id  Time
0       win  102    10
1      fail  303     0
2  Not fail  944     0
3       win  111    23
4       win  675     0
5   Not win  236     0
jpp
  • 159,742
  • 34
  • 281
  • 339