DougKruger DougKruger - 1 month ago 5
Python Question

Find row in pandas and update specific value

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
?

Answer

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