user9292
user9292

Reputation: 1145

Using If-else to change values in Pandas

I’ve a pd df consists three columns: ID, t, and ind1.

import pandas as pd
dat = {'ID': [1,1,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,6],
        't': [0,1,2,3,0,1,2,0,1,2,3,0,1,2,0,1,0,1,2],
        'ind1' : [1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0]
        }

df = pd.DataFrame(dat, columns = ['ID', 't', 'ind1'])

print (df)

What I need to do is to create a new column (res) that

Here’s anticipated output

enter image description here

Upvotes: 3

Views: 90

Answers (3)

sammywemmy
sammywemmy

Reputation: 28709

This works on the knowledge that the ID column is sorted :

cond1 = df.ind1.eq(0)
cond2 = df.ind1.eq(1) & (df.t.eq(df.groupby("ID").t.transform("max")))

df["res"] = np.select([cond1, cond2], [0, 1], 0)

df


   ID   t ind1 res
0   1   0   1   0
1   1   1   1   0
2   1   2   1   0
3   1   3   1   1
4   2   0   0   0
5   2   1   0   0
6   2   2   0   0
7   3   0   0   0
8   3   1   0   0
9   3   2   0   0
10  3   3   0   0
11  4   0   1   0
12  4   1   1   0
13  4   2   1   1
14  5   0   1   0
15  5   1   1   1
16  6   0   0   0
17  6   1   0   0
18  6   2   0   0

Upvotes: 2

Space Impact
Space Impact

Reputation: 13255

Use groupby.apply:

df['res'] = (df.groupby('ID').apply(lambda x: x['ind1'].eq(1)&x['t'].eq(x['t'].max()))
               .astype(int).reset_index(drop=True))

print(df)
    ID  t  ind1  res
0    1  0     1    0
1    1  1     1    0
2    1  2     1    0
3    1  3     1    1
4    2  0     0    0
5    2  1     0    0
6    2  2     0    0
7    3  0     0    0
8    3  1     0    0
9    3  2     0    0
10   3  3     0    0
11   4  0     1    0
12   4  1     1    0
13   4  2     1    1
14   5  0     1    0
15   5  1     1    1
16   6  0     0    0
17   6  1     0    0
18   6  2     0    0

Upvotes: 1

BENY
BENY

Reputation: 323326

Check with groupby with idxmax , then where with transform all

df['res']=df.groupby('ID').t.transform('idxmax').where(df.groupby('ID').ind1.transform('all')).eq(df.index).astype(int)
df
Out[160]: 
    ID  t  ind1  res
0    1  0     1    0
1    1  1     1    0
2    1  2     1    0
3    1  3     1    1
4    2  0     0    0
5    2  1     0    0
6    2  2     0    0
7    3  0     0    0
8    3  1     0    0
9    3  2     0    0
10   3  3     0    0
11   4  0     1    0
12   4  1     1    0
13   4  2     1    1
14   5  0     1    0
15   5  1     1    1
16   6  0     0    0
17   6  1     0    0
18   6  2     0    0

Upvotes: 4

Related Questions