简体   繁体   中英

Replace cell values from pandas dataframe

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

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
x["isPreviousEventNotFailNotWin"] = ((x.Event == "Not fail") | (x.Event == "Not win")).shift(-1)
x.Time[x.isPreviousEventNotFailNotWin == True] = 0

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM