How to merge specific values in pandas df column

I’m sure this problem would be somewhere in SO but I can’t find it anywhere. How can you merge specific values in a pandas column? For the df below I only want to merge values in Col A,B when they are Foo,Bar and leave everything else.

import pandas as pd

d = ({
    'A' : ['Foo','No'],
    'B' : ['Bar','Bar'],
   })

df = pd.DataFrame(data=d)

If I do this:

df["A"] = df["A"].map(str) + df["B"] 

        A    B
0  FooBar  Bar
1   NoBar  Bar

Where as I’m hoping to output:

        A    B
0  FooBar     
1      No  Bar

Answer

IIUC,

idx=(df.A == 'Foo' )& (df.B == 'Bar')
df.loc[idx, 'A']  = df.loc[idx, 'A'] + df.loc[idx, 'B']
df.loc[idx, 'B'] = ''

    A       B
0   FooBar  
1   No      Bar

Leave a Reply

Your email address will not be published. Required fields are marked *