jeudi 20 août 2020

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

  • for all ID with ind1==0, then res is zero.
  • for all ID with ind1==1 and if t==max(t) (group by ID), then res = 1, otherwise zero.

Here’s anticipated output

enter image description here

Aucun commentaire:

Enregistrer un commentaire