在pandas中查找行并更新特定值

时间:2016-11-01 09:11:16

标签: python pandas

我有一个包含id, uid, gid, tstamp列的数据框。我可以通过执行df[df['id'] == 12]找到特定的行,该行提供:

     id   uid   gid    tstamp
711  12   CA    CA-1   47585768600

如何更新uidgid的值CAINCA-1IN-1

1 个答案:

答案 0 :(得分:4)

您可以ix选择并将值设置为['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

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