pandas conditional loc append values

374 Views Asked by At

I have the following df

d = {'col1': [1, 2], 'col2': [3, 4], 'col3':["dog", "cat"]}
df = pd.DataFrame(data=d)

col1    col2    col3
0   1   3   dog
1   2   4   cat

If I wanted to change the value in col3 in rows which col1=1 and col2=3 to fox I would do:

df.loc[(df.col1==1)&(df.col2==3), "col3"]="fox"

 col1   col2    col3
    0   1   3   fox
    1   2   4   cat

Instead of changing dog to fox I want to append it, like so:

col1    col2    col3
0   1   3   dog, fox
1   2   4   cat

How can I do this?

2

There are 2 best solutions below

0
On

Just join them using +

df.loc[(df.col1==1)&(df.col2==3), "col3"] = df.loc[(df.col1==1)&(df.col2==3), "col3"] + ', ' + "fox"

Out[383]:
   col1  col2      col3
0     1     3  dog, fox
1     2     4       cat
0
On

Use the += operator:

df.loc[(df.col1==1)&(df.col2==3), 'col3'] += ', fox'

   col1  col2      col3
0     1     3  dog, fox
1     2     4       cat