How can I conditionally add columns (string) together in pandas Data Frame?

Viewed 48

I need to add column A to B. I could achive this by doing this:

import pandas as pd

sample_dict = {
               'A' : ["entry", "", "", "entry"],
               'B' : ["foo", "foo", "", ""]
              }
sample_frame = pd.DataFrame(sample_dict)
sample_frame['A'] = sample_frame['A'] + sample_frame['B']
del sample_frame['B']

Then I end up with:

          A
0  entryfoo
1       foo
2          
3     entry

While the two columns are now one, I can hardly distinguish between the two values. What I want is this:

            A
0  entry, foo
1         foo
2          
3       entry

So I want to put a ", " in between the values, but only if one of the values is not "". Otherwise I end up with this if I just use sample_frame['A'] = sample_frame['A'] + ", " + sample_frame['B']:

            A
0  entry, foo
1       , foo
2           ,      
3      entry, 

So, how can I achive this conditional addition?

1 Answers

Even your solution is fine, just strip off the leftovers at last, using Series.str.strip:

sample_frame['A'] = (sample_frame['A'] + ", " + sample_frame['B']).str.strip(', ')

OUTPUT:

            A
0  entry, foo
1         foo
2            
3       entry
Related