Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row in pandas and update specific value

Tags:

python

pandas

I have a dataframe with columns id, uid, gid, tstamp. I'm able to locate a specific row by doing df[df['id'] == 12] which gives:

     id   uid   gid    tstamp
711  12   CA    CA-1   47585768600

How can I update the value of uid and gid say from CA to IN and CA-1 to IN-1?

like image 801
DougKruger Avatar asked Nov 01 '16 09:11

DougKruger


1 Answers

You can select by ix and set values to ['IN','IN-1']:

print (df)
     id uid   gid       tstamp
711  12  CA  CA-1  47585768600
711  15  CA  CA-1  47585768600

df.ix[df['id'] == 12, ['uid','gid']] = ['IN','IN-1']

print (df)
     id uid   gid       tstamp
711  12  IN  IN-1  47585768600
711  15  CA  CA-1  47585768600

Another solution with replace:

df.ix[df['id'] == 12, ['uid','gid']] = 
df.ix[df['id'] == 12, ['uid','gid']].replace({'CA':'IN'}, regex=True)

print (df)
     id uid   gid       tstamp
711  12  IN  IN-1  47585768600
711  15  CA  CA-1  47585768600
like image 108
jezrael Avatar answered Sep 22 '22 22:09

jezrael